package cn.stylefeng.guns.modular.transport.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import cn.stylefeng.guns.base.dict.SystemDict;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.modular.agv.model.params.FeedbackTaskRS;
import cn.stylefeng.guns.modular.agv.service.HikAgvTaskService;
import cn.stylefeng.guns.modular.agv.util.HikApiUtils;
import cn.stylefeng.guns.modular.agv.util.HikRsVo;
import cn.stylefeng.guns.modular.agv.util.TustApiUtils;
import cn.stylefeng.guns.modular.basic.entity.BasicPrivatecar;
import cn.stylefeng.guns.modular.basic.model.params.BasicCarrierParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicCustomerParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicPrivatecarParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicXlbOauth2tokenParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicCarrierResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicCustomerResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicPrivatecarResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicXlbOauth2tokenResult;
import cn.stylefeng.guns.modular.basic.service.*;
import cn.stylefeng.guns.modular.hx.order.entity.HxOrderOut;
import cn.stylefeng.guns.modular.hx.order.entity.HxOrderOutDetailed;
import cn.stylefeng.guns.modular.hx.order.model.result.HxOrderOutResult;
import cn.stylefeng.guns.modular.hx.order.service.HxOrderOutDetailedService;
import cn.stylefeng.guns.modular.hx.order.service.HxOrderOutService;
import cn.stylefeng.guns.modular.hx.storage.entity.HxCollectionLocation;
import cn.stylefeng.guns.modular.hx.storage.entity.HxStorageOut;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStorageStockParam;
import cn.stylefeng.guns.modular.hx.storage.service.HxCollectionLocationService;
import cn.stylefeng.guns.modular.hx.storage.service.HxStorageOutService;
import cn.stylefeng.guns.modular.hx.storage.service.HxStorageStockService;
import cn.stylefeng.guns.modular.order.entity.OrderTransport;
import cn.stylefeng.guns.modular.order.model.params.OrderOutpreparePlatooncarParam;
import cn.stylefeng.guns.modular.order.model.params.OrderTransportParam;
import cn.stylefeng.guns.modular.order.model.result.OrderOutpreparePlatooncarResult;
import cn.stylefeng.guns.modular.order.model.result.OrderTransportResult;
import cn.stylefeng.guns.modular.order.service.OrderOutpreparePlatooncarService;
import cn.stylefeng.guns.modular.order.service.OrderTransportService;
import cn.stylefeng.guns.modular.rest.transport.vo.TrayNumberVo;
import cn.stylefeng.guns.modular.storage.model.params.StorageOutParam;
import cn.stylefeng.guns.modular.storage.model.result.StorageOutResult;
import cn.stylefeng.guns.modular.storage.service.StorageOutService;
import cn.stylefeng.guns.modular.transport.entity.*;
import cn.stylefeng.guns.modular.transport.model.PlatooncarVo;
import cn.stylefeng.guns.modular.transport.model.params.*;
import cn.stylefeng.guns.modular.transport.model.result.*;
import cn.stylefeng.guns.modular.transport.model.vo.CkdPrintItemOby;
import cn.stylefeng.guns.modular.transport.model.vo.CkdPrintOby;
import cn.stylefeng.guns.modular.transport.service.*;
import cn.stylefeng.guns.modular.transport.utils.XlbApiUtils;
import cn.stylefeng.guns.sys.modular.system.entity.Dept;
import cn.stylefeng.guns.sys.modular.system.entity.Role;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.model.result.DictResult;
import cn.stylefeng.guns.sys.modular.system.service.*;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 调度单表控制器
 */
@Controller
@RequestMapping("/tDispatch")
public class TDispatchController extends BaseController {

    private String PREFIX = "/transport/tDispatch";

    @Autowired
    private TDispatchService tDispatchService;

    @Autowired
    private TransportDispatchService transportDispatchService;

    @Autowired
    private UserService userService;

    @Autowired
    private TransportReceiptService transportReceiptService;

    @Autowired
    private BasicOperateService basicOperateService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private BasicCarrierService basicCarrierService;

    @Autowired
    private OrderOutpreparePlatooncarService orderOutpreparePlatooncarService;

    @Autowired
    private InwarehouseTrackService inwarehouseTrackService;

    @Autowired
    private HxOrderOutService hxOrderOutService;

    @Autowired
    private HxOrderOutDetailedService hxOrderOutDetailedService;

    @Value("${hxl.api.url}")
    private String hxlApiUrl;

    @Value("${file.tmpImpPath}")
    private String tmpImpPath;

    /**
     * 跳转到 好想来TMS监控
     */
    @RequestMapping("hx_totmsmonitor")
    public String hx_totmsmonitor(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId, deliverId, user.getOperateId()));
        return PREFIX + "/tmsmonitor.html";
    }

    /**
     * 查询 好想来待装车列表
     */
    @ResponseBody
    @RequestMapping("/list_driverSignin2")
    public LayuiPageInfo list_driverSignin2(TransportMsgParam transportMsgParam, String condition, String startTime, String endTime) {
        if (transportMsgParam.getOperateId() == null) {
            LayuiPageInfo layuiPageInfo = new LayuiPageInfo();
            return layuiPageInfo;
        }

        User user = userService.getcurrentUser();
        transportMsgParam.setStatus("到仓签到");
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            transportMsgParam.setTimes("'" + startTime + "' and '" + endTime + "'");
        } else if (startTime == null && endTime == null) {
            startTime = DateUtil.getDate();
            endTime = DateUtil.getDate();
            transportMsgParam.setTimes("'" + startTime + "' and '" + endTime + "'");
        }
        transportMsgParam.setDeptId(user.getDeptId());

        //查看当前账户是否是承运商，若是承运商只能查看自己的数据
        BasicCarrierResult basicCarrier = basicCarrierService.findBySpec(BasicCarrierParam.builder()
                .deptId(user.getDeptId())
                .carrierAccount(user.getAccount())
                .build(), user.getOperateId());
        if (basicCarrier != null) {
            transportMsgParam.setCarrierId(basicCarrier.getId().longValue());
        }

        List<TransportMsgResult> list = this.transportMsgService.finddriverSigninPageBySpec2(transportMsgParam, condition, user.getOperateId());

        //根据当前时间，获取已排车记录
        OrderOutpreparePlatooncarParam orderOutpreparePlatooncarParam = new OrderOutpreparePlatooncarParam();
        orderOutpreparePlatooncarParam.setDeptId(user.getDeptId());
        orderOutpreparePlatooncarParam.setDeliverId(user.getDeliverId());
        orderOutpreparePlatooncarParam.setStatNotIn("已拒绝");
        orderOutpreparePlatooncarParam.setV1(DateUtil.getDate());

        List<OrderOutpreparePlatooncarResult> listBySpec = null;
        String roleId = user.getRoleId();
        if (ToolUtil.isNotEmpty(roleId)) {
            for (String rId : roleId.split(",")) {
                Role byId = roleService.getById(rId);
                if (byId != null && byId.getName().contains("总部")) {
                    listBySpec = orderOutpreparePlatooncarService.findListBySpec(orderOutpreparePlatooncarParam, transportMsgParam.getOperateId());
                } else {
                    listBySpec = orderOutpreparePlatooncarService.findListBySpec(orderOutpreparePlatooncarParam, user.getOperateId());
                }
            }
        }

        List<String> client_ids = new ArrayList<String>();
        Map<String, Set<String>> sijidianhuaClientMap = new HashMap<String, Set<String>>();
        Map<String, String> clientMap = new HashMap<>();
        for (OrderOutpreparePlatooncarResult obj : listBySpec) {
            if (ToolUtil.isNotEmpty(obj.getClientId())) {
                client_ids.add(obj.getClientId());
            }
            clientMap.put(obj.getClientId(), obj.getClientName());
            if (sijidianhuaClientMap.get(obj.getSijidianhua()) == null) {
                Set set = new HashSet();
                set.add(obj.getClientId());
                sijidianhuaClientMap.put(obj.getSijidianhua(), set);
            } else {
                sijidianhuaClientMap.get(obj.getSijidianhua()).add(obj.getClientId());
            }
        }
        //调用接口，获取待拣货和待质检数量
        BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
        oauth2tokenParam.setDeliverId(user.getDeliverId());

        if (transportMsgParam.getOperateId() != null && transportMsgParam.getOperateId() == 42) {
            oauth2tokenParam.setGsnumber("68668");
        } else if (user.getOperateId() != null && user.getOperateId() == 42) {
            oauth2tokenParam.setGsnumber("68668");
        } else {
            oauth2tokenParam.setGsnumber("66666");
        }
        BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);
        Map<String, PlatooncarVo> prePickOrder = new HashMap<>();
        if (oauth2tokenResult != null) {
            prePickOrder = XlbApiUtils.findPrePickOrder(this.hxlApiUrl, client_ids, oauth2tokenResult.getOauth2TokenXlb());
        }
        //循环遍历
        for (TransportMsgResult _transportMsgResult : list) {
            String v2 = _transportMsgResult.getV2();
            if (sijidianhuaClientMap.get(v2) != null) {
                int i = 1;
                PlatooncarVo platooncarVo = null;
                for (String key : sijidianhuaClientMap.get(v2)) {
                    if (prePickOrder.get(key) != null) {
                        platooncarVo = prePickOrder.get(key);
                        if (i == 1) {
                            StringBuffer str = new StringBuffer();
                            str.append(clientMap.get(key));
                            str.append("</br>");
                            str.append("拣[").append(platooncarVo.getPrePickOrderCount()).append("]|检[").append(platooncarVo.getPreCheckOrderCount()).append("]");
                            _transportMsgResult.setMendian1(str.toString());
                            if (platooncarVo.getPrePickOrderCount() == 0 && platooncarVo.getPreCheckOrderCount() == 0) {
                                _transportMsgResult.setMendian1Ok("OK");
                            }
                        } else if (i == 2) {
                            StringBuffer str = new StringBuffer();
                            str.append(clientMap.get(key));
                            str.append("</br>");
                            str.append("拣[").append(platooncarVo.getPrePickOrderCount()).append("]|检[").append(platooncarVo.getPreCheckOrderCount()).append("]");
                            _transportMsgResult.setMendian2(str.toString());
                            if (platooncarVo.getPrePickOrderCount() == 0 && platooncarVo.getPreCheckOrderCount() == 0) {
                                _transportMsgResult.setMendian2Ok("OK");
                            }
                        } else if (i == 3) {
                            StringBuffer str = new StringBuffer();
                            str.append(clientMap.get(key));
                            str.append("</br>");
                            str.append("拣[").append(platooncarVo.getPrePickOrderCount()).append("]|检[").append(platooncarVo.getPreCheckOrderCount()).append("]");
                            _transportMsgResult.setMendian3(str.toString());
                            if (platooncarVo.getPrePickOrderCount() == 0 && platooncarVo.getPreCheckOrderCount() == 0) {
                                _transportMsgResult.setMendian3Ok("OK");
                            }
                        } else if (i == 4) {
                            StringBuffer str = new StringBuffer();
                            str.append(clientMap.get(key));
                            str.append("</br>");
                            str.append("拣[").append(platooncarVo.getPrePickOrderCount()).append("]|检[").append(platooncarVo.getPreCheckOrderCount()).append("]");
                            _transportMsgResult.setMendian4(str.toString());
                            if (platooncarVo.getPrePickOrderCount() == 0 && platooncarVo.getPreCheckOrderCount() == 0) {
                                _transportMsgResult.setMendian4Ok("OK");
                            }
                        } else if (i == 5) {
                            StringBuffer str = new StringBuffer();
                            str.append(clientMap.get(key));
                            str.append("</br>");
                            str.append("拣[").append(platooncarVo.getPrePickOrderCount()).append("]|检[").append(platooncarVo.getPreCheckOrderCount()).append("]");
                            _transportMsgResult.setMendian5(str.toString());
                            if (platooncarVo.getPrePickOrderCount() == 0 && platooncarVo.getPreCheckOrderCount() == 0) {
                                _transportMsgResult.setMendian5Ok("OK");
                            }
                        } else if (i == 6) {
                            StringBuffer str = new StringBuffer();
                            str.append(clientMap.get(key));
                            str.append("</br>");
                            str.append("拣[").append(platooncarVo.getPrePickOrderCount()).append("]|检[").append(platooncarVo.getPreCheckOrderCount()).append("]");
                            _transportMsgResult.setMendian6(str.toString());
                            if (platooncarVo.getPrePickOrderCount() == 0 && platooncarVo.getPreCheckOrderCount() == 0) {
                                _transportMsgResult.setMendian6Ok("OK");
                            }
                        } else if (i == 7) {
                            StringBuffer str = new StringBuffer();
                            str.append(clientMap.get(key));
                            str.append("</br>");
                            str.append("拣[").append(platooncarVo.getPrePickOrderCount()).append("]|检[").append(platooncarVo.getPreCheckOrderCount()).append("]");
                            _transportMsgResult.setMendian7(str.toString());
                            if (platooncarVo.getPrePickOrderCount() == 0 && platooncarVo.getPreCheckOrderCount() == 0) {
                                _transportMsgResult.setMendian7Ok("OK");
                            }
                        } else if (i == 8) {
                            StringBuffer str = new StringBuffer();
                            str.append(clientMap.get(key));
                            str.append("</br>");
                            str.append("拣[").append(platooncarVo.getPrePickOrderCount()).append("]|检[").append(platooncarVo.getPreCheckOrderCount()).append("]");
                            _transportMsgResult.setMendian8(str.toString());
                            if (platooncarVo.getPrePickOrderCount() == 0 && platooncarVo.getPreCheckOrderCount() == 0) {
                                _transportMsgResult.setMendian8Ok("OK");
                            }
                        } else if (i == 9) {
                            StringBuffer str = new StringBuffer();
                            str.append(clientMap.get(key));
                            str.append("</br>");
                            str.append("拣[").append(platooncarVo.getPrePickOrderCount()).append("]|检[").append(platooncarVo.getPreCheckOrderCount()).append("]");
                            _transportMsgResult.setMendian9(str.toString());
                            if (platooncarVo.getPrePickOrderCount() == 0 && platooncarVo.getPreCheckOrderCount() == 0) {
                                _transportMsgResult.setMendian9Ok("OK");
                            }
                        } else if (i == 10) {
                            StringBuffer str = new StringBuffer();
                            str.append(clientMap.get(key));
                            str.append("</br>");
                            str.append("拣[").append(platooncarVo.getPrePickOrderCount()).append("]|检[").append(platooncarVo.getPreCheckOrderCount()).append("]");
                            _transportMsgResult.setMendian10(str.toString());
                            if (platooncarVo.getPrePickOrderCount() == 0 && platooncarVo.getPreCheckOrderCount() == 0) {
                                _transportMsgResult.setMendian10Ok("OK");
                            }
                        }
                        i++;
                    }
                }
            }
        }

        LayuiPageInfo layuiPageInfo = new LayuiPageInfo();
        layuiPageInfo.setData(list);
        layuiPageInfo.setCount(list.size());
        return layuiPageInfo;
    }


    /**
     * 查询 好想来装车进度列表
     */
    @ResponseBody
    @RequestMapping("/hx_zhuangchejindu")
    public LayuiPageInfo hx_zhuangchejindu(TDispatchParam tDispatchParam, String condition, String startTime, String endTime) {
        User user = userService.getcurrentUser();
        tDispatchParam.setDeptId(user.getDeptId());
        tDispatchParam.setDeliverId(user.getDeliverId());
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            tDispatchParam.setStartDate("'" + startTime + "' and '" + endTime + "'");
        } else if (startTime == null && endTime == null) {
            startTime = DateUtil.getDate();
            endTime = DateUtil.getDate();
            tDispatchParam.setStartDate("'" + startTime + "' and '" + endTime + "'");
        }

        //查看当前账户是否是承运商，若是承运商只能查看自己的数据
        BasicCarrierResult basicCarrier = basicCarrierService.findBySpec(BasicCarrierParam.builder()
                .deptId(user.getDeptId())
                .carrierAccount(user.getAccount())
                .build(), user.getOperateId());
        if (basicCarrier != null) {
            tDispatchParam.setCarrierId(basicCarrier.getId().longValue());
        }

        List<TDispatchResult> list = this.tDispatchService.findHxzhuangchejindu(tDispatchParam, condition, user.getOperateId());
        LayuiPageInfo layuiPageInfo = new LayuiPageInfo();
        layuiPageInfo.setData(list);
        layuiPageInfo.setCount(list.size());
        return layuiPageInfo;
    }

    /**
     * 查询 好想来配送进度列表
     */
    @ResponseBody
    @RequestMapping("/hx_peisongjindu")
    public LayuiPageInfo hx_peisongjindu(TransportDispatchParam transportDispatchParam, String condition, String startTime, String endTime, Long operateId) {
        User user = userService.getcurrentUser();
        transportDispatchParam.setDeptId(user.getDeptId());
        transportDispatchParam.setDeliverId(user.getDeliverId());
        String times = "";
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            times = "'" + startTime + "' and '" + endTime + "'";
        } else if (startTime == null && endTime == null) {
            startTime = DateUtil.getDate();
            endTime = DateUtil.getDate();
            times = "'" + startTime + "' and '" + endTime + "'";
        }
        List<SjCntVo> sjCntList = tDispatchService.getSJCnt();
        Map<String, SjCntVo> sjCntMap = new HashMap<>();
        for (SjCntVo obj : sjCntList) {
            sjCntMap.put(obj.getSijidianhua(), obj);
        }
        //查看当前账户是否是承运商，若是承运商只能查看自己的数据
        BasicCarrierResult basicCarrier = basicCarrierService.findBySpec(BasicCarrierParam.builder()
                .deptId(user.getDeptId())
                .carrierAccount(user.getAccount())
                .build(), user.getOperateId());
        if (basicCarrier != null) {
            transportDispatchParam.setCarrierId(basicCarrier.getId().longValue());
        }
        List<ZhuangyunMingxiTongji> list = this.transportDispatchService.findPeisongjindu(transportDispatchParam, condition, times, operateId, user.getOperateId());
        String dispatchNumber = "";
        for (ZhuangyunMingxiTongji r : list) {
            if (ToolUtil.isEmpty(dispatchNumber)) {
                dispatchNumber = r.getDispatchNumber();
                TDispatchParam dispatchParam = new TDispatchParam();
                dispatchParam.setDispatchNumber(r.getDispatchNumber());
                TDispatchResult tDispatchResult = tDispatchService.findBySpecAndCar(dispatchParam);
                if (tDispatchResult != null) {
                    r.setStartDate(tDispatchResult.getStartDate());
                    r.setCarrierName(tDispatchResult.getCarrierName());
                    r.setCarnumber(tDispatchResult.getCarnumber());
                    r.setPrivatecarType(tDispatchResult.getPrivatecarType());
                    r.setDriver1(tDispatchResult.getDriver1());
                    r.setTel1(tDispatchResult.getTel1());
                    r.setCarrierName(tDispatchResult.getCarrierName());
                    r.setFulllv(tDispatchResult.getFulllv());
                    r.setZhuangzaiFileid(tDispatchResult.getZhuangzaiFileid());
                    r.setFayunTimes(tDispatchResult.getFayunTimes());
                    r.setDaocangTimes(tDispatchResult.getShijidaocangshijian());
                    r.setDriverEvalFlag(tDispatchResult.getDriverEvalFlag());
                }
            } else {
                if (!dispatchNumber.equals(r.getDispatchNumber())) {
                    dispatchNumber = r.getDispatchNumber();
                    TDispatchParam dispatchParam = new TDispatchParam();
                    dispatchParam.setDispatchNumber(r.getDispatchNumber());
                    TDispatchResult tDispatchResult = tDispatchService.findBySpecAndCar(dispatchParam);
                    if (tDispatchResult != null) {
                        r.setStartDate(tDispatchResult.getStartDate());
                        r.setCarrierName(tDispatchResult.getCarrierName());
                        r.setCarnumber(tDispatchResult.getCarnumber());
                        r.setPrivatecarType(tDispatchResult.getPrivatecarType());
                        r.setDriver1(tDispatchResult.getDriver1());
                        r.setTel1(tDispatchResult.getTel1());
                        r.setCarrierName(tDispatchResult.getCarrierName());
                        r.setFulllv(tDispatchResult.getFulllv());
                        r.setZhuangzaiFileid(tDispatchResult.getZhuangzaiFileid());
                        r.setFayunTimes(tDispatchResult.getFayunTimes());
                        r.setDaocangTimes(tDispatchResult.getShijidaocangshijian());
                        r.setDriverEvalFlag(tDispatchResult.getDriverEvalFlag());
                    }
                }
            }
        }
        List<ZhuangyunMingxiTongji> res = new ArrayList<ZhuangyunMingxiTongji>();
        ZhuangyunMingxiTongji tj = new ZhuangyunMingxiTongji();
        String dispatchNumber2 = "";
        int ji = 1;
        int jiok = 0;
        for (ZhuangyunMingxiTongji r : list) {
            if (ToolUtil.isEmpty(dispatchNumber2)) {
                dispatchNumber2 = r.getDispatchNumber();
                tj.setGetUnit(ji + r.getGetUnit());
                tj.setReachTime(r.getReachTime());

                tj.setStartDate(r.getStartDate());
                tj.setCarrierName(r.getCarrierName());
                tj.setCarnumber(r.getCarnumber());
                tj.setPrivatecarType(r.getPrivatecarType());
                tj.setDriver1(r.getDriver1());
                tj.setTel1(r.getTel1());
                tj.setCarrierName(r.getCarrierName());
                tj.setFulllv(r.getFulllv());
                tj.setZhuangzaiFileid(r.getZhuangzaiFileid());
                tj.setFayunTimes(r.getFayunTimes());
                tj.setDaocangTimes(r.getDaocangTimes());

                tj.setHandoverTime(r.getHandoverTime());
                tj.setSubtime(r.getSubtime());
                tj.setDriverEvalFlag(r.getDriverEvalFlag());
                //司机配送次数
                if (sjCntMap.get(r.getTel1()) != null) {
                    tj.setSjCnt(sjCntMap.get(r.getTel1()).getCnt());
                }
                if (ToolUtil.isNotEmpty(r.getReachTime())) {
                    jiok++;
                }
            } else {
                if (!dispatchNumber2.equals(r.getDispatchNumber())) {
                    if (jiok == 0) {
                        tj.setJindu("0");
                    } else {
                        Double jiokd = Double.parseDouble(jiok + "");
                        Double jid = Double.parseDouble(ji + "");
                        String format = new DecimalFormat("#.00").format(jiokd / jid * 100);
                        tj.setJindu(format);
                    }
                    res.add(tj);
                    dispatchNumber2 = r.getDispatchNumber();
                    ji = 1;
                    jiok = 0;
                    tj = new ZhuangyunMingxiTongji();

                    tj.setGetUnit(ji + r.getGetUnit());
                    tj.setReachTime(r.getReachTime());
                    tj.setHandoverTime(r.getHandoverTime());
                    tj.setSubtime(r.getSubtime());

                    tj.setStartDate(r.getStartDate());
                    tj.setCarrierName(r.getCarrierName());
                    tj.setCarnumber(r.getCarnumber());
                    tj.setPrivatecarType(r.getPrivatecarType());
                    tj.setDriver1(r.getDriver1());
                    tj.setTel1(r.getTel1());
                    tj.setCarrierName(r.getCarrierName());
                    tj.setMileageTraveled(r.getMileageTraveled());
                    tj.setFulllv(r.getFulllv());
                    tj.setZhuangzaiFileid(r.getZhuangzaiFileid());
                    tj.setFayunTimes(r.getFayunTimes());
                    tj.setDaocangTimes(r.getDaocangTimes());
                    tj.setDriverEvalFlag(r.getDriverEvalFlag());
                    //司机配送次数
                    if (sjCntMap.get(r.getTel1()) != null) {
                        tj.setSjCnt(sjCntMap.get(r.getTel1()).getCnt());
                    }

                    if (ToolUtil.isNotEmpty(r.getReachTime())) {
                        jiok++;
                    }
                } else {
                    if (ji == 1) {
                        tj.setGetUnit1((ji + 1) + r.getGetUnit());
                        tj.setReachTime1(r.getReachTime());
                        tj.setHandoverTime1(r.getHandoverTime());
                        tj.setSubtime1(r.getSubtime());
                    }
                    if (ji == 2) {
                        tj.setGetUnit2((ji + 1) + r.getGetUnit());
                        tj.setReachTime2(r.getReachTime());
                        tj.setHandoverTime2(r.getHandoverTime());
                        tj.setSubtime2(r.getSubtime());
                    }
                    if (ji == 3) {
                        tj.setGetUnit3((ji + 1) + r.getGetUnit());
                        tj.setReachTime3(r.getReachTime());
                        tj.setHandoverTime3(r.getHandoverTime());
                        tj.setSubtime3(r.getSubtime());
                    }
                    if (ji == 4) {
                        tj.setGetUnit4((ji + 1) + r.getGetUnit());
                        tj.setReachTime4(r.getReachTime());
                        tj.setHandoverTime4(r.getHandoverTime());
                        tj.setSubtime4(r.getSubtime());
                    }
                    if (ji == 5) {
                        tj.setGetUnit5((ji + 1) + r.getGetUnit());
                        tj.setReachTime5(r.getReachTime());
                        tj.setHandoverTime5(r.getHandoverTime());
                        tj.setSubtime5(r.getSubtime());
                    }
                    if (ji == 6) {
                        tj.setGetUnit6((ji + 1) + r.getGetUnit());
                        tj.setReachTime6(r.getReachTime());
                        tj.setHandoverTime6(r.getHandoverTime());
                        tj.setSubtime6(r.getSubtime());
                    }
                    if (ji == 7) {
                        tj.setGetUnit7((ji + 1) + r.getGetUnit());
                        tj.setReachTime7(r.getReachTime());
                        tj.setHandoverTime7(r.getHandoverTime());
                        tj.setSubtime7(r.getSubtime());
                    }
                    if (ji == 8) {
                        tj.setGetUnit8((ji + 1) + r.getGetUnit());
                        tj.setReachTime8(r.getReachTime());
                        tj.setHandoverTime8(r.getHandoverTime());
                        tj.setSubtime8(r.getSubtime());
                    }
                    if (ji == 9) {
                        tj.setGetUnit9((ji + 1) + r.getGetUnit());
                        tj.setReachTime9(r.getReachTime());
                        tj.setHandoverTime9(r.getHandoverTime());
                        tj.setSubtime9(r.getSubtime());
                    }
                    if (ToolUtil.isNotEmpty(r.getReachTime())) {
                        jiok++;
                    }
                    ji++;
                }
            }
        }
        if (ToolUtil.isNotEmpty(dispatchNumber2)) {
            if (jiok == 0) {
                tj.setJindu("0");
            } else {
                Double jiokd = Double.parseDouble(jiok + "");
                Double jid = Double.parseDouble(ji + "");
                String format = new DecimalFormat("#.00").format(jiokd / jid * 100);
                tj.setJindu(format);
            }
            res.add(tj);
        }
        //根据配送进度排序
        res.sort((u4, u5) -> {
            Double age1 = Double.parseDouble(u4.getJindu());
            Double age2 = Double.parseDouble(u5.getJindu());
            return age1.compareTo(age2);
        });
        //添加%
        for (ZhuangyunMingxiTongji r : res) {
            r.setFulllv(r.getFulllv() + "%");
            r.setJindu(r.getJindu() + "%");
        }
        LayuiPageInfo layuiPageInfo = new LayuiPageInfo();
        layuiPageInfo.setData(res);
        layuiPageInfo.setCount(res.size());
        return layuiPageInfo;
    }

    /**
     * 跳转到 好想来承运商发运分析
     */
    @RequestMapping("hx_tochengyunshanganalysis")
    public String hx_tochengyunshanganalysis(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId, deliverId, user.getOperateId()));
        return PREFIX + "/hxchengyunshanganalysis.html";
    }

    /**
     * 跳转到 好想来承运商发运分析
     */
    @RequestMapping("hx_tochengyunshanganalysis2")
    public String hx_tochengyunshanganalysis2(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId, deliverId, user.getOperateId()));
        return PREFIX + "/hxchengyunshanganalysis2.html";
    }

    /**
     * 查询 好想来承运商发运分析列表
     */
    @ResponseBody
    @RequestMapping("/hxchengyunshanganalysis")
    public LayuiPageInfo hxchengyunshanganalysis(TDispatchParam tDispatchParam, String condition, String startTime, String endTime) {
        User user = userService.getcurrentUser();
        tDispatchParam.setDeptId(user.getDeptId());
        tDispatchParam.setDeliverId(user.getDeliverId());
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            tDispatchParam.setStartDate("'" + startTime + "' and '" + endTime + "'");
        } else if (startTime == null && endTime == null) {
            startTime = DateUtil.getDate();
            endTime = DateUtil.getDate();
            tDispatchParam.setStartDate("'" + startTime + "' and '" + endTime + "'");
        }


        //查看当前账户是否是承运商，若是承运商只能查看自己的数据
        BasicCarrierResult basicCarrier = basicCarrierService.findBySpec(BasicCarrierParam.builder()
                .deptId(user.getDeptId())
                .carrierAccount(user.getAccount())
                .build(), user.getOperateId());
        if (basicCarrier != null) {
            tDispatchParam.setCarrierId(basicCarrier.getId().longValue());
        }

        List<Hxchengyunshanganalysis> list = this.tDispatchService.findHxchengyunshanganalysis(tDispatchParam, condition, user.getOperateId());
        BigDecimal as = new BigDecimal("0");
        Map<String, BigDecimal> sumMap = new HashMap<>();
        for (Hxchengyunshanganalysis hx : list) {
            if (hx.getCarrierId() != null) {
                BigDecimal zongtiji = new BigDecimal(hx.getZongtiji());//总体积
                BigDecimal zongjianshu = new BigDecimal(hx.getZongjianshu());//总件数
                BigDecimal zonglicheng = new BigDecimal(hx.getZonglicheng());//总里程
                BigDecimal zongyunfei = new BigDecimal(hx.getZongyunfei());//总运费
                //总体积
                if (sumMap.get("zongtiji") == null) {
                    sumMap.put("zongtiji", zongtiji);
                } else {
                    sumMap.put("zongtiji", sumMap.get("zongtiji").add(zongtiji));
                }
                //总件数
                if (sumMap.get("zongjianshu") == null) {
                    sumMap.put("zongjianshu", zongjianshu);
                } else {
                    sumMap.put("zongjianshu", sumMap.get("zongjianshu").add(zongjianshu));
                }
                //总里程
                if (sumMap.get("zonglicheng") == null) {
                    sumMap.put("zonglicheng", zonglicheng);
                } else {
                    sumMap.put("zonglicheng", sumMap.get("zonglicheng").add(zonglicheng));
                }
                //总运费
                if (sumMap.get("zongyunfei") == null) {
                    sumMap.put("zongyunfei", zongyunfei);
                } else {
                    sumMap.put("zongyunfei", sumMap.get("zongyunfei").add(zongyunfei));
                }

                TDispatchParam countcheci = new TDispatchParam();
                countcheci.setCarrierId(hx.getCarrierId());
                countcheci.setStartDate(tDispatchParam.getStartDate());
                Integer countchecis = tDispatchService.countcheci(countcheci);//实发车次
                hx.setShifacheci(countchecis + "");
                BigDecimal countchecisbig = new BigDecimal(countchecis + "");
                //实发车次
                if (sumMap.get("countchecisbig") == null) {
                    sumMap.put("countchecisbig", countchecisbig);
                } else {
                    sumMap.put("countchecisbig", sumMap.get("countchecisbig").add(countchecisbig));
                }
                TransportMsgParam msgParam = new TransportMsgParam();
                msgParam.setCarrierId(hx.getCarrierId());
                msgParam.setTimes(tDispatchParam.getStartDate());
                msgParam.setStatus("到仓签到");
                msgParam.setDeptId(hx.getDeptId());
                Integer countqiandaochecis = transportMsgService.countqiandaocheci(msgParam, hx.getOperateId());//签到车次
                hx.setQiandaocheci(countqiandaochecis + "");

                TransportDispatchParam dispatchParam = new TransportDispatchParam();
                dispatchParam.setCarrierId(hx.getCarrierId());
                dispatchParam.setStartDate(tDispatchParam.getStartDate());
                TransportDispatchResult sumMatrixingNumber = transportDispatchService.sumMatrixingNumberByCarrierId(dispatchParam);//换算数量
                BigDecimal sumMatrixingNumberbig = new BigDecimal("0");
                if (sumMatrixingNumber == null) {
                    sumMatrixingNumberbig = zongjianshu;
                    hx.setHuansuanjianshu("0");
                } else {
                    hx.setHuansuanjianshu(sumMatrixingNumber.getMatrixingNumber());
                    sumMatrixingNumberbig = new BigDecimal(sumMatrixingNumber.getMatrixingNumber());
                }
                //换算数量
                if (sumMap.get("sumMatrixingNumberbig") == null) {
                    sumMap.put("sumMatrixingNumberbig", sumMatrixingNumberbig);
                } else {
                    sumMap.put("sumMatrixingNumberbig", sumMap.get("sumMatrixingNumberbig").add(sumMatrixingNumberbig));
                }
                BigDecimal junchetiji = zongtiji.divide(countchecisbig, 3, BigDecimal.ROUND_HALF_DOWN);//均车体积
                hx.setJunchetiji(junchetiji.toString());

                BigDecimal juncheshuliang = sumMatrixingNumberbig.divide(countchecisbig, 3, BigDecimal.ROUND_HALF_DOWN);//均车数量
                hx.setJuncheshuliang(juncheshuliang.toString());

                if (zonglicheng.compareTo(as) == 1) {
                    BigDecimal junchelicheng = zonglicheng.divide(countchecisbig, 3, BigDecimal.ROUND_HALF_DOWN);//均车里程
                    hx.setJunchelicheng(junchelicheng.toString());
                } else {
                    hx.setJunchelicheng("0");
                }

                if (zongyunfei.compareTo(as) == 0) {
                    hx.setJuncheyunfei("0");
                    hx.setJunjianyunfei("0");
                    hx.setJunjian1gongli("0");

                } else if (zongyunfei.compareTo(as) == 1) {
                    BigDecimal juncheyunfei = zongyunfei.divide(countchecisbig, 3, BigDecimal.ROUND_HALF_DOWN);//均车运费
                    hx.setJuncheyunfei(juncheyunfei.toString());

                    BigDecimal junjianyunfei = zongyunfei.divide(sumMatrixingNumberbig, 3, BigDecimal.ROUND_HALF_DOWN);//均件运费
                    hx.setJunjianyunfei(junjianyunfei.toString());

                    if (zonglicheng.compareTo(as) == 1) {
                        BigDecimal junjian1gongli = junjianyunfei.divide(zonglicheng, 3, BigDecimal.ROUND_HALF_DOWN);//均件/公里
                        hx.setJunjian1gongli(junjian1gongli.toString());
                    } else {
                        hx.setJunjian1gongli("0");
                    }
                }
            }
        }
        Map<String, BigDecimal> mapSum = new HashMap<>();
        LayuiPageInfo layuiPageInfo = new LayuiPageInfo();
        layuiPageInfo.setData(list);
        try {
            //计算均值
            if (sumMap.get("countchecisbig") != null) {
                mapSum.put("junchetiji", sumMap.get("zongtiji").divide(sumMap.get("countchecisbig"), 3, BigDecimal.ROUND_HALF_DOWN));
                mapSum.put("juncheshuliang", sumMap.get("sumMatrixingNumberbig").divide(sumMap.get("countchecisbig"), 3, BigDecimal.ROUND_HALF_DOWN));
                mapSum.put("junchelicheng", sumMap.get("zonglicheng").divide(sumMap.get("countchecisbig"), 3, BigDecimal.ROUND_HALF_DOWN));
                mapSum.put("juncheyunfei", sumMap.get("zongyunfei").divide(sumMap.get("countchecisbig"), 3, BigDecimal.ROUND_HALF_DOWN));
                mapSum.put("junjianyunfei", sumMap.get("zongyunfei").divide(sumMap.get("sumMatrixingNumberbig"), 3, BigDecimal.ROUND_HALF_DOWN));
                mapSum.put("jungongliyunfei", sumMap.get("zongyunfei").divide(sumMap.get("zonglicheng"), 3, BigDecimal.ROUND_HALF_DOWN));
                mapSum.put("junjian1gongli", mapSum.get("junjianyunfei").divide(sumMap.get("zonglicheng"), 3, BigDecimal.ROUND_HALF_DOWN));
                mapSum.put("junfang1gongli", sumMap.get("zongyunfei").divide(sumMap.get("zongtiji"), 3, BigDecimal.ROUND_HALF_DOWN).divide(sumMap.get("zonglicheng"), 3, BigDecimal.ROUND_HALF_DOWN));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        layuiPageInfo.setTotalRow(mapSum);
        layuiPageInfo.setCount(list.size());
        return layuiPageInfo;
    }

    /**
     * 跳转到 好想来发运装载量统计
     */
    @RequestMapping("hx_tozhaungzaicount")
    public String hx_tozhaungzaicount(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId, deliverId, user.getOperateId()));
        return PREFIX + "/hxzhaungzaicount.html";
    }

    /**
     * 查询 好想来发运装载量列表
     */
    @ResponseBody
    @RequestMapping("/hxzhaungzaicount")
    public LayuiPageInfo hxzhaungzaicount(TDispatchParam tDispatchParam, String condition, String startTime, String endTime) {
        User user = userService.getcurrentUser();
        tDispatchParam.setDeptId(user.getDeptId());
        tDispatchParam.setDeliverId(user.getDeliverId());
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            tDispatchParam.setStartDate("'" + startTime + "' and '" + endTime + "'");
        } else if (startTime == null && endTime == null) {
            startTime = DateUtil.getDate();
            endTime = DateUtil.getDate();
            tDispatchParam.setStartDate("'" + startTime + "' and '" + endTime + "'");
        }

        //查看当前账户是否是承运商，若是承运商只能查看自己的数据
        String roleId = user.getRoleId();
        if (ToolUtil.isNotEmpty(roleId)) {
            for (String rId : roleId.split(",")) {
                Role byId = roleService.getById(rId);
                if (byId != null && byId.getName().contains("承运商")) {
                    BasicCarrierParam param = new BasicCarrierParam();
                    param.setUserId(user.getUserId());
                    BasicCarrierResult bySpec = basicCarrierService.findBySpec(param, user.getOperateId());
                    if (bySpec != null) {
                        tDispatchParam.setCarrierId(Long.valueOf(bySpec.getId()));
                    } else {
                        tDispatchParam.setCarrierId(-1L);
                    }
                }
            }
        }
//        BasicCarrierResult basicCarrier = basicCarrierService.findBySpec(BasicCarrierParam.builder()
//                .deptId(user.getDeptId())
//                .carrierAccount(user.getAccount())
//                .build(), user.getOperateId());
//        if(basicCarrier != null){
//            tDispatchParam.setCarrierId(basicCarrier.getId().longValue());
//        }

        List<TDispatchResult> list = this.tDispatchService.findHxzhaungzaicount(tDispatchParam, condition, user.getOperateId());
        LayuiPageInfo layuiPageInfo = new LayuiPageInfo();
        layuiPageInfo.setData(list);
        layuiPageInfo.setCount(list.size());
        return layuiPageInfo;
    }

    /**
     * 跳转到 好想来台账
     */
    @RequestMapping("hx_totaizhang")
    public String hx_totaizhang(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId, deliverId, user.getOperateId()));
        return PREFIX + "/hxtaizhang.html";
    }

    /**
     * 查询 好想来台账列表
     */
    @ResponseBody
    @RequestMapping("/hxtaizhang")
    public LayuiPageInfo hxtaizhang(TDispatchParam tDispatchParam, String condition, String startTime, String endTime) {
        User user = userService.getcurrentUser();
        tDispatchParam.setDeptId(user.getDeptId());
        tDispatchParam.setDeliverId(user.getDeliverId());
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            tDispatchParam.setStartDate("'" + startTime + "' and '" + endTime + "'");
        } else if (startTime == null && endTime == null) {
            startTime = DateUtil.getDate();
            endTime = DateUtil.getDate();
            tDispatchParam.setStartDate("'" + startTime + "' and '" + endTime + "'");
        }

        String roleId = user.getRoleId();
        if (ToolUtil.isNotEmpty(roleId)) {
            for (String rId : roleId.split(",")) {
                Role byId = roleService.getById(rId);
                if (byId != null && byId.getName().contains("承运商")) {
                    BasicCarrierParam param = new BasicCarrierParam();
                    param.setUserId(user.getUserId());
                    BasicCarrierResult bySpec = basicCarrierService.findBySpec(param, user.getOperateId());
                    if (bySpec != null) {
                        tDispatchParam.setCarrierId(Long.valueOf(bySpec.getId()));
                    } else {
                        tDispatchParam.setCarrierId(-1L);
                    }
                }
            }
        }
        List<TDispatchResult> list = this.tDispatchService.findHxtaizhang(tDispatchParam, condition, user.getOperateId());
        List<Hxtaizhang> res = new ArrayList<Hxtaizhang>();
        for (TDispatchResult r : list) {
            Hxtaizhang hxtaizhang = new Hxtaizhang();
            hxtaizhang.setOperateName(r.getOperateName());
            hxtaizhang.setOrderNumber(r.getTrainNumber());
            hxtaizhang.setStartDate(r.getStartDate());
            hxtaizhang.setGetUnitName(r.getGetUnits());
            hxtaizhang.setLineName(r.getLineName());
            hxtaizhang.setCarNumber(r.getCarnumber());
            hxtaizhang.setZhuangzaicishu(r.getZhuangzaicishu());
            hxtaizhang.setCarType(r.getChexing());
            hxtaizhang.setSiji(r.getSiji());
            hxtaizhang.setSijidianhua(r.getSijidianhua());
            hxtaizhang.setMileageTraveled(r.getMileageTraveled());
            hxtaizhang.setToovolume(r.getToovolume());
            hxtaizhang.setLoadingPersonnel(r.getLoadingPersonnel());
            hxtaizhang.setCarrierName(r.getCarrierName());
            hxtaizhang.setZuiwandaodianshijian(r.getZuiwandaodianshijian());
            hxtaizhang.setFayunjishi("否");
            if (ToolUtil.isNotEmpty(r.getFayunTimes()) && ToolUtil.isNotEmpty(r.getShijidaocangshijian())) {
                try {
                    LocalTime FayunTimes = LocalTime.parse(r.getFayunTimes(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    LocalTime shijidaocangshijian = LocalTime.parse(r.getShijidaocangshijian(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    Duration duration = Duration.between(shijidaocangshijian, FayunTimes);
                    hxtaizhang.setFayunsjc(duration.toHours() + "时" + (duration.toMinutes() % 60) + "分");
                    if (duration.toMinutes() <= 150) {
                        hxtaizhang.setFayunjishi("是");
                    }
                } catch (Exception e) {
                    // e.printStackTrace();
                }
            }

            if (ToolUtil.isNotEmpty(r.getShijidaocangshijian()) && r.getShijidaocangshijian().split(" ").length > 1) {
                hxtaizhang.setShijidaocangrq(r.getShijidaocangshijian().split(" ")[0]);
                hxtaizhang.setShijidaocangshijian(r.getShijidaocangshijian().split(" ")[1]);//实际到仓时间
            }
            if (ToolUtil.isNotEmpty(r.getFayunTimes()) && r.getFayunTimes().split(" ").length > 1) {
                hxtaizhang.setStartTime(r.getFayunTimes().split(" ")[1]);//发车时间
            }

            hxtaizhang.setZuizaodaodianshijian(r.getZuizaodaodianshijian());//最早到店时间
            hxtaizhang.setHuidan(r.getReturnTstate());
            hxtaizhang.setFreightMoney(r.getFreightMoney());
            hxtaizhang.setZhuangchefei(r.getLoadingMoney());
            hxtaizhang.setMatrixingNumber(r.getMatrixingNumber());
            hxtaizhang.setPieceNumberSum(r.getPieceNumberSum());
            //发运日期 最早到点日期 比较
            if (ToolUtil.isNotEmpty(r.getFayunTimes()) && ToolUtil.isNotEmpty(r.getZuiwandaodianshijian())) {
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    int date1 = sdf.parse(r.getFayunTimes()).getDate();
                    int date2 = sdf.parse(r.getZuiwandaodianshijian()).getDate();
                    int cha = date2 - date1;
                    if (cha < 1) {
                        hxtaizhang.setJrd("即日达");
                    } else if (cha < 2) {
                        hxtaizhang.setJrd("次日达");
                    } else if (cha < 3) {
                        hxtaizhang.setJrd("3日达");
                    } else {
                        hxtaizhang.setJrd("多日达");
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            res.add(hxtaizhang);
        }
        LayuiPageInfo layuiPageInfo = new LayuiPageInfo();
        layuiPageInfo.setData(res);
        layuiPageInfo.setCount(res.size());
        return layuiPageInfo;
    }

    /**
     * 跳转到 配送分析
     */
    @RequestMapping("peisong_fenxi")
    public String peisong_fenxi(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId, deliverId, user.getOperateId()));
        return PREFIX + "/peisongFenxi.html";
    }

    /**
     * 查询 配送分析
     */
    @ResponseBody
    @RequestMapping("/findPeisongfenxiAll")
    public List<peisongfenxi> findPeisongfenxiAll(TransportDispatchParam transportDispatchParam, String condition, String startTime, String endTime, String getUnit
            , Long operateId) {
        User user = userService.getcurrentUser();
        transportDispatchParam.setDeptId(user.getDeptId());
        String times = "";
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            times = "'" + startTime + "' and '" + endTime + "'";
        } else if (startTime == null && endTime == null) {
            startTime = DateUtil.getDate();
            endTime = DateUtil.getDate();
            times = "'" + startTime + "' and '" + endTime + "'";
        }
        List<peisongfenxi> list = this.transportDispatchService.findPeisongfenxi(transportDispatchParam, condition, getUnit, times, operateId, user.getOperateId());
        return list;
    }

    /**
     * 查询 配送分析
     */
    @ResponseBody
    @RequestMapping("/findPeisongfenxiPage")
    public LayuiPageInfo findPeisongfenxiPage(TransportDispatchParam transportDispatchParam, String condition, String startTime, String endTime, String getUnit
            , Long operateId) {
        User user = userService.getcurrentUser();
        transportDispatchParam.setDeptId(user.getDeptId());
        String times = "";
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            times = "'" + startTime + "' and '" + endTime + "'";
        } else if (startTime == null && endTime == null) {
            startTime = DateUtil.getDate();
            endTime = DateUtil.getDate();
            times = "'" + startTime + "' and '" + endTime + "'";
        }
        return this.transportDispatchService.findPeisongfenxiPage(transportDispatchParam, condition, getUnit, times, operateId, user.getOperateId());
    }

    /**
     * 跳转到 承运商装运汇总统计
     */
    @RequestMapping("chengyunshangcount")
    public String chengyunshangcount(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();

        //查询可选择分公司
        model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId, deliverId, user.getOperateId()));
        return PREFIX + "/chengyunshangCount.html";
    }

    /**
     * 查询 承运商装运汇总统计列表
     */
    @ResponseBody
    @RequestMapping("/findchengyunshangcount")
    public LayuiPageInfo findchengyunshangcount(TDispatchParam tDispatchParam, String condition, String startTime, String endTime, String driver1) {
        User user = userService.getcurrentUser();
        tDispatchParam.setDeptId(user.getDeptId());
        tDispatchParam.setDeliverId(user.getDeliverId());
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            tDispatchParam.setMoney("'" + startTime + "' and '" + endTime + "'");
        } else if (startTime == null && endTime == null) {
            startTime = DateUtil.getDate();
            endTime = DateUtil.getDate();
            tDispatchParam.setMoney("'" + startTime + "' and '" + endTime + "'");
        }
        List<TDispatchResult> list = this.tDispatchService.findchengyunshangcount(tDispatchParam, condition, driver1, user.getOperateId());
        LayuiPageInfo layuiPageInfo = new LayuiPageInfo();
        layuiPageInfo.setData(list);
        layuiPageInfo.setCount(list.size());
        return layuiPageInfo;
    }

    /**
     * 跳转到 承运商装运明细统计
     */
    @RequestMapping("chengyunshang_mingxicount")
    public String chengyunshang_mingxicount(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId, deliverId, user.getOperateId()));
        return PREFIX + "/chengyunshangMingxiCount.html";
    }

    /**
     * 查询 承运商装运明细统计列表
     */
    @ResponseBody
    @RequestMapping("/findchengyunshangMingxiCount")
    public LayuiPageInfo findchengyunshangMingxiCount(TransportDispatchParam transportDispatchParam, String condition, String startTime, String endTime, String getUnit
            , Long operateId) {
        User user = userService.getcurrentUser();
        transportDispatchParam.setDeptId(user.getDeptId());
        transportDispatchParam.setDeliverId(user.getDeliverId());
        String times = "";
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            times = "'" + startTime + "' and '" + endTime + "'";
        } else if (startTime == null && endTime == null) {
            startTime = DateUtil.getDate();
            endTime = DateUtil.getDate();
            times = "'" + startTime + "' and '" + endTime + "'";
        }
        List<ZhuangyunMingxiTongji> list = this.transportDispatchService.findchengyunshangMingxiCount(transportDispatchParam, condition, getUnit, times, operateId, user.getOperateId());
        String dispatchNumber = "";
        for (ZhuangyunMingxiTongji r : list) {
            if (ToolUtil.isEmpty(dispatchNumber)) {
                dispatchNumber = r.getDispatchNumber();
                r.setDispatchNumber2(r.getDispatchNumber());
                TDispatchParam dispatchParam = new TDispatchParam();
                dispatchParam.setDispatchNumber(r.getDispatchNumber());
                TDispatchResult tDispatchResult = tDispatchService.findBySpecAndCar(dispatchParam);
                if (tDispatchResult != null) {
                    r.setTrainNumber(tDispatchResult.getTrainNumber());
                    r.setCarnumber(tDispatchResult.getCarnumber());
                    r.setTooNum(tDispatchResult.getTooNum());
                    r.setMatrixingNumberSum(tDispatchResult.getMatrixingNumber());
                    r.setToovolume(tDispatchResult.getToovolume());
                    r.setToomoney(tDispatchResult.getToomoney());
                    r.setMoney(tDispatchResult.getMoney());
                    r.setFulllv(tDispatchResult.getFulllv());
                    r.setFayunTimes(tDispatchResult.getFayunTimes());
                    r.setTel1(tDispatchResult.getTel1());
                    r.setDriver1(tDispatchResult.getDriver1());
                    r.setPrivatecarType(tDispatchResult.getPrivatecarType());
                    r.setNotes(tDispatchResult.getNotes());
                    r.setMileageTraveled(tDispatchResult.getMileageTraveled());
                    r.setLoadingType(tDispatchResult.getLoadingType());
                    r.setLoadingPersonnel(tDispatchResult.getLoadingPersonnel());
                    r.setPrivatecarSurevolume(tDispatchResult.getPrivatecarSurevolume());

                    r.setChengyunfangshi(tDispatchResult.getChengyunfangshi());
                    r.setChengyunleixing(tDispatchResult.getChengyunleixing());
                    r.setCarrierName(tDispatchResult.getCarrierName());
                    r.setXiechefei(tDispatchResult.getXiechefei());
                    r.setLoadingMoney(tDispatchResult.getLoadingMoney());
                    r.setFreightMoney(tDispatchResult.getFreightMoney());
                    r.setConsultMoney(tDispatchResult.getConsultMoney());
                }
            } else {
                if (!dispatchNumber.equals(r.getDispatchNumber())) {
                    dispatchNumber = r.getDispatchNumber();
                    r.setDispatchNumber2(r.getDispatchNumber());
                    TDispatchParam dispatchParam = new TDispatchParam();
                    dispatchParam.setDispatchNumber(r.getDispatchNumber());
                    TDispatchResult tDispatchResult = tDispatchService.findBySpecAndCar(dispatchParam);
                    if (tDispatchResult != null) {
                        r.setTrainNumber(tDispatchResult.getTrainNumber());
                        r.setCarnumber(tDispatchResult.getCarnumber());
                        r.setTooNum(tDispatchResult.getTooNum());
                        r.setMatrixingNumberSum(tDispatchResult.getMatrixingNumber());
                        r.setToovolume(tDispatchResult.getToovolume());
                        r.setToomoney(tDispatchResult.getToomoney());
                        r.setMoney(tDispatchResult.getMoney());
                        r.setFulllv(tDispatchResult.getFulllv());
                        r.setFayunTimes(tDispatchResult.getFayunTimes());
                        r.setTel1(tDispatchResult.getTel1());
                        r.setDriver1(tDispatchResult.getDriver1());
                        r.setPrivatecarType(tDispatchResult.getPrivatecarType());
                        r.setNotes(tDispatchResult.getNotes());
                        r.setMileageTraveled(tDispatchResult.getMileageTraveled());
                        r.setLoadingType(tDispatchResult.getLoadingType());
                        r.setLoadingPersonnel(tDispatchResult.getLoadingPersonnel());
                        r.setPrivatecarSurevolume(tDispatchResult.getPrivatecarSurevolume());

                        r.setChengyunfangshi(tDispatchResult.getChengyunfangshi());
                        r.setChengyunleixing(tDispatchResult.getChengyunleixing());
                        r.setCarrierName(tDispatchResult.getCarrierName());
                        r.setXiechefei(tDispatchResult.getXiechefei());
                        r.setLoadingMoney(tDispatchResult.getLoadingMoney());
                        r.setFreightMoney(tDispatchResult.getFreightMoney());
                        r.setConsultMoney(tDispatchResult.getConsultMoney());
                    }
                } else {
                    r.setDispatchNumber("");
                    r.setDispatchNumber2(dispatchNumber);
                }
            }
        }
        for (ZhuangyunMingxiTongji r : list) {
            if (ToolUtil.isNotEmpty(r.getDispatchNumber())) {
                BigDecimal pieceNumberSum = new BigDecimal("0");
                for (ZhuangyunMingxiTongji r2 : list) {
                    if (r.getDispatchNumber().equals(r2.getDispatchNumber2())) {
                        if (ToolUtil.isNotEmpty(r2.getPieceNumber())) {
                            BigDecimal pieceNumber = new BigDecimal(r2.getPieceNumber());
                            pieceNumberSum = pieceNumberSum.add(pieceNumber).setScale(2, BigDecimal.ROUND_HALF_DOWN);
                        }
                    }
                }
                r.setPieceNumberSum(pieceNumberSum + "");
            }
        }
        LayuiPageInfo layuiPageInfo = new LayuiPageInfo();
        layuiPageInfo.setData(list);
        layuiPageInfo.setCount(list.size());
        return layuiPageInfo;
    }

    /**
     * 查询 承运商装运明细统计列表
     */
    @ResponseBody
    @RequestMapping("/findchengyunshangMingxiAll")
    public List<ZhuangyunMingxiTongji> findchengyunshangMingxiAll(TransportDispatchParam transportDispatchParam, String condition, String startTime, String endTime, String getUnit
            , Long operateId) {
        User user = userService.getcurrentUser();
        transportDispatchParam.setDeptId(user.getDeptId());
        transportDispatchParam.setDeliverId(user.getDeliverId());
        String times = "";
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            times = "'" + startTime + "' and '" + endTime + "'";
        } else if (startTime == null && endTime == null) {
            startTime = DateUtil.getDate();
            endTime = DateUtil.getDate();
            times = "'" + startTime + "' and '" + endTime + "'";
        }
        String roleId = user.getRoleId();
        if (ToolUtil.isNotEmpty(roleId)) {
            for (String rId : roleId.split(",")) {
                Role byId = roleService.getById(rId);
                if (byId != null && byId.getName().contains("承运商")) {
                    BasicCarrierParam param = new BasicCarrierParam();
                    param.setUserId(user.getUserId());
                    BasicCarrierResult bySpec = basicCarrierService.findBySpec(param, user.getOperateId());
                    if (bySpec != null) {
                        transportDispatchParam.setCarrierId(Long.valueOf(bySpec.getId()));
                    } else {
                        transportDispatchParam.setCarrierId(-1L);
                    }
                }
            }
        }
        return this.transportDispatchService.findchengyunshangMingxiAll(transportDispatchParam, condition, getUnit, times, operateId, user.getOperateId());
    }

    /**
     * 查询 承运商装运明细统计列表
     */
    @ResponseBody
    @RequestMapping("/findchengyunshangMingxiPage")
    public LayuiPageInfo findchengyunshangMingxiPage(TransportDispatchParam transportDispatchParam, String condition, String startTime, String endTime, String getUnit
            , Long operateId) {
        User user = userService.getcurrentUser();
        transportDispatchParam.setDeptId(user.getDeptId());
        transportDispatchParam.setDeliverId(user.getDeliverId());
        String times = "";
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            times = "'" + startTime + "' and '" + endTime + "'";
        } else if (startTime == null && endTime == null) {
            startTime = DateUtil.getDate();
            endTime = DateUtil.getDate();
            times = "'" + startTime + "' and '" + endTime + "'";
        }
        String roleId = user.getRoleId();
        if (ToolUtil.isNotEmpty(roleId)) {
            for (String rId : roleId.split(",")) {
                Role byId = roleService.getById(rId);
                if (byId != null && byId.getName().contains("承运商")) {
                    BasicCarrierParam param = new BasicCarrierParam();
                    param.setUserId(user.getUserId());
                    BasicCarrierResult bySpec = basicCarrierService.findBySpec(param, user.getOperateId());
                    if (bySpec != null) {
                        transportDispatchParam.setCarrierId(Long.valueOf(bySpec.getId()));
                    } else {
                        transportDispatchParam.setCarrierId(-1L);
                    }
                }
            }
        }
        return this.transportDispatchService.findchengyunshangMingxiPage(transportDispatchParam, condition, getUnit, times, operateId, user.getOperateId());
    }

    /**
     * 跳转到 承运商装运客户统计
     */
    @RequestMapping("chengyunshang_getunitcount")
    public String chengyunshang_getunitcount(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId, deliverId, user.getOperateId()));
        return PREFIX + "/chengyunshangGetUnitCount.html";
    }

    /**
     * 查询 承运商装运客户统计列表
     */
    @ResponseBody
    @RequestMapping("/findchengyunshangGetUnitCount")
    public LayuiPageInfo findchengyunshangGetUnitCount(TransportDispatchParam transportDispatchParam, String condition, String startTime, String endTime, String getUnit
            , Long operateId) {
        User user = userService.getcurrentUser();
        transportDispatchParam.setDeptId(user.getDeptId());
        transportDispatchParam.setDeliverId(user.getDeliverId());
        String times = "";
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            times = "'" + startTime + "' and '" + endTime + "'";
        } else if (startTime == null && endTime == null) {
            startTime = DateUtil.getDate();
            endTime = DateUtil.getDate();
            times = "'" + startTime + "' and '" + endTime + "'";
        }
        List<ZhuangyunMingxiTongji> list = this.transportDispatchService.findchengyunshangGetUnitCount(transportDispatchParam, condition, getUnit, times, operateId, user.getOperateId());
        String dispatchNumber = "";
        for (ZhuangyunMingxiTongji r : list) {
            if (ToolUtil.isEmpty(dispatchNumber)) {
                dispatchNumber = r.getDispatchNumber();
                TDispatchParam dispatchParam = new TDispatchParam();
                dispatchParam.setDispatchNumber(r.getDispatchNumber());
                TDispatchResult tDispatchResult = tDispatchService.findBySpecAndCar(dispatchParam);
                if (tDispatchResult != null) {
                    r.setTrainNumber(tDispatchResult.getTrainNumber());
                    r.setCarnumber(tDispatchResult.getCarnumber());
                    r.setTooNum(tDispatchResult.getTooNum());
                    r.setMatrixingNumberSum(tDispatchResult.getMatrixingNumber());
                    r.setToovolume(tDispatchResult.getToovolume());
                    r.setToomoney(tDispatchResult.getToomoney());
                    r.setMoney(tDispatchResult.getMoney());
                    r.setFulllv(tDispatchResult.getFulllv());
                    r.setStartDate(tDispatchResult.getStartDate());
                    r.setDaocangTimes(tDispatchResult.getShijidaocangshijian());
                    r.setFayunTimes(tDispatchResult.getFayunTimes());
                    r.setTel1(tDispatchResult.getTel1());
                    r.setDriver1(tDispatchResult.getDriver1());
                    r.setPrivatecarType(tDispatchResult.getPrivatecarType());
                    r.setMileageTraveled(tDispatchResult.getMileageTraveled());
                    r.setLoadingType(tDispatchResult.getLoadingType());
                    r.setLoadingPersonnel(tDispatchResult.getLoadingPersonnel());
                    r.setPrivatecarSurevolume(tDispatchResult.getPrivatecarSurevolume());

                    r.setOperateName(tDispatchResult.getOperateName());
                    r.setLineName(tDispatchResult.getLineName());
                    r.setChengyunfangshi(tDispatchResult.getChengyunfangshi());
                    r.setChengyunleixing(tDispatchResult.getChengyunleixing());
                    r.setCarrierName(tDispatchResult.getCarrierName());
                    r.setXiechefei(tDispatchResult.getXiechefei());
                    r.setLoadingMoney(tDispatchResult.getLoadingMoney());
                    r.setFreightMoney(tDispatchResult.getFreightMoney());
                    r.setConsultMoney(tDispatchResult.getConsultMoney());
                }
            } else {
                if (!dispatchNumber.equals(r.getDispatchNumber())) {
                    dispatchNumber = r.getDispatchNumber();
                    TDispatchParam dispatchParam = new TDispatchParam();
                    dispatchParam.setDispatchNumber(r.getDispatchNumber());
                    TDispatchResult tDispatchResult = tDispatchService.findBySpecAndCar(dispatchParam);
                    if (tDispatchResult != null) {
                        r.setTrainNumber(tDispatchResult.getTrainNumber());
                        r.setCarnumber(tDispatchResult.getCarnumber());
                        r.setTooNum(tDispatchResult.getTooNum());
                        r.setMatrixingNumberSum(tDispatchResult.getMatrixingNumber());
                        r.setToovolume(tDispatchResult.getToovolume());
                        r.setToomoney(tDispatchResult.getToomoney());
                        r.setMoney(tDispatchResult.getMoney());
                        r.setFulllv(tDispatchResult.getFulllv());
                        r.setStartDate(tDispatchResult.getStartDate());
                        r.setDaocangTimes(tDispatchResult.getShijidaocangshijian());
                        r.setFayunTimes(tDispatchResult.getFayunTimes());
                        r.setTel1(tDispatchResult.getTel1());
                        r.setDriver1(tDispatchResult.getDriver1());
                        r.setPrivatecarType(tDispatchResult.getPrivatecarType());
                        r.setMileageTraveled(tDispatchResult.getMileageTraveled());
                        r.setLoadingType(tDispatchResult.getLoadingType());
                        r.setLoadingPersonnel(tDispatchResult.getLoadingPersonnel());
                        r.setPrivatecarSurevolume(tDispatchResult.getPrivatecarSurevolume());

                        r.setOperateName(tDispatchResult.getOperateName());
                        r.setLineName(tDispatchResult.getLineName());
                        r.setChengyunfangshi(tDispatchResult.getChengyunfangshi());
                        r.setChengyunleixing(tDispatchResult.getChengyunleixing());
                        r.setCarrierName(tDispatchResult.getCarrierName());
                        r.setXiechefei(tDispatchResult.getXiechefei());
                        r.setLoadingMoney(tDispatchResult.getLoadingMoney());
                        r.setFreightMoney(tDispatchResult.getFreightMoney());
                        r.setConsultMoney(tDispatchResult.getConsultMoney());
                    }
                } else {
                    r.setDispatchNumber("");
                }
            }
        }
        LayuiPageInfo layuiPageInfo = new LayuiPageInfo();
        layuiPageInfo.setData(list);
        layuiPageInfo.setCount(list.size());
        return layuiPageInfo;
    }

    /**
     * 查询 承运商装运客户统计列表
     */
    @ResponseBody
    @RequestMapping("/findchengyunshangGetUnitCountPage")
    public LayuiPageInfo findchengyunshangGetUnitCountPage(TransportDispatchParam transportDispatchParam, String condition, String startTime, String endTime, String getUnit
            , Long operateId) {
        User user = userService.getcurrentUser();
        transportDispatchParam.setDeptId(user.getDeptId());
        transportDispatchParam.setDeliverId(user.getDeliverId());
        String times = "";
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            times = "'" + startTime + "' and '" + endTime + "'";
        } else if (startTime == null && endTime == null) {
            startTime = DateUtil.getDate();
            endTime = DateUtil.getDate();
            times = "'" + startTime + "' and '" + endTime + "'";
        }

        String roleId = user.getRoleId();
        if (ToolUtil.isNotEmpty(roleId)) {
            for (String rId : roleId.split(",")) {
                Role byId = roleService.getById(rId);
                if (byId != null && byId.getName().contains("承运商")) {
                    BasicCarrierParam param = new BasicCarrierParam();
                    param.setUserId(user.getUserId());
                    BasicCarrierResult bySpec = basicCarrierService.findBySpec(param, user.getOperateId());
                    if (bySpec != null) {
                        transportDispatchParam.setCarrierId(Long.valueOf(bySpec.getId()));
                    } else {
                        transportDispatchParam.setCarrierId(-1L);
                    }
                }
            }
        }

        return this.transportDispatchService.findchengyunshangGetUnitCountPage(transportDispatchParam, condition, getUnit, times, operateId, user.getOperateId());
    }

    /**
     * 查询 承运商装运客户统计列表
     */
    @ResponseBody
    @RequestMapping("/findchengyunshangGetUnitCountAll")
    public List<ZhuangyunMingxiTongji> findchengyunshangGetUnitCountAll(TransportDispatchParam transportDispatchParam, String condition, String startTime, String endTime, String getUnit
            , Long operateId) {
        User user = userService.getcurrentUser();
        transportDispatchParam.setDeptId(user.getDeptId());
        transportDispatchParam.setDeliverId(user.getDeliverId());
        String times = "";
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            times = "'" + startTime + "' and '" + endTime + "'";
        } else if (startTime == null && endTime == null) {
            startTime = DateUtil.getDate();
            endTime = DateUtil.getDate();
            times = "'" + startTime + "' and '" + endTime + "'";
        }

        String roleId = user.getRoleId();
        if (ToolUtil.isNotEmpty(roleId)) {
            for (String rId : roleId.split(",")) {
                Role byId = roleService.getById(rId);
                if (byId != null && byId.getName().contains("承运商")) {
                    BasicCarrierParam param = new BasicCarrierParam();
                    param.setUserId(user.getUserId());
                    BasicCarrierResult bySpec = basicCarrierService.findBySpec(param, user.getOperateId());
                    if (bySpec != null) {
                        transportDispatchParam.setCarrierId(Long.valueOf(bySpec.getId()));
                    } else {
                        transportDispatchParam.setCarrierId(-1L);
                    }
                }
            }
        }
        return this.transportDispatchService.findchengyunshangGetUnitCountAll(transportDispatchParam, condition, getUnit, times, operateId, user.getOperateId());
    }

    /**
     * 跳转到 承运商装运明细统计
     */
    @RequestMapping("chengyunshang_mingxicount2")
    public String chengyunshang_mingxicount2(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId, deliverId, user.getOperateId()));
        return PREFIX + "/chengyunshangMingxiCount2.html";
    }

    /**
     * 查询 承运商装运明细统计列表
     */
    @ResponseBody
    @RequestMapping("/findchengyunshangMingxiCount2")
    public LayuiPageInfo findchengyunshangMingxiCount2(TransportReceiptParam transportReceiptParam, String condition, String startTime, String endTime, String driver1) {
        transportReceiptParam.setDeptId(userService.getDeptId());
        transportReceiptParam.setDeliverId(userService.getDeliverId());
        String money = "";
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            money = "'" + startTime + "' and '" + endTime + "'";
        } else if (startTime == null && endTime == null) {
            startTime = DateUtil.getDate();
            endTime = DateUtil.getDate();
            money = "'" + startTime + "' and '" + endTime + "'";
        }
        List<TransportReceiptResult> list = this.transportReceiptService.findchengyunshangMingxiCount(transportReceiptParam, condition, driver1, money);
        LayuiPageInfo layuiPageInfo = new LayuiPageInfo();
        layuiPageInfo.setData(list);
        layuiPageInfo.setCount(list.size());
        return layuiPageInfo;
    }

    /**
     * 跳转到运输单查询
     */
    @RequestMapping("")
    public String index(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId, deliverId, user.getOperateId()));
        return PREFIX + "/tDispatch.html";
    }

    /**
     * 跳转到运输单审核
     */
    @RequestMapping("tDispatch_examine")
    public String tDispatch_examine() {
        return PREFIX + "/tDispatch_examine.html";
    }

    /**
     * 跳转到运输单执行
     */
    @RequestMapping("Implement")
    public String Implement(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId, deliverId, user.getOperateId()));
        return PREFIX + "/tDispatch_implement.html";
    }

    /**
     * 跳转到运输单执行
     */
    @RequestMapping("tDispatchStateTbMgr")
    public String tDispatchStateTbMgr(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId, deliverId, user.getOperateId()));
        return "/fi/tDispatchStateTbMgr/tDispatchStateTbMgr.html";
    }

    /**
     * 跳转到修改
     */
    @RequestMapping("toedit")
    public String toedit(Model model) {
        User user = userService.getcurrentUser();
        BasicPrivatecarParam param = new BasicPrivatecarParam();
        List<BasicPrivatecarResult> carlist = basicPrivatecarService.findListBySpec(param, user.getDeptId(), user.getOperateId());
        model.addAttribute("carlist", carlist);
        return PREFIX + "/edit.html";
    }

    @Autowired
    private TransportMsgService transportMsgService;

    /**
     * 到仓装车
     */
    @RequestMapping("/editdaocang")
    @ResponseBody
    public ResponseData editdaocang(TDispatchParam tDispatchParam) {
        User user = userService.getcurrentUser();
        TDispatchResult dispatchResult = tDispatchService.findBySpec(tDispatchParam, null);
        if (dispatchResult != null) {
            if (dispatchResult.getTstate().equals("已定价")) {
                tDispatchParam.setTstate("待发运");
                this.tDispatchService.update(tDispatchParam);

                TransportMsgParam transportMsgParam = new TransportMsgParam();
                transportMsgParam.setDispatchNumber(dispatchResult.getDispatchNumber());
                transportMsgParam.setStatus("到仓装车");
                transportMsgParam.setMsgType("系统");
                transportMsgParam.setContent(dispatchResult.getCarnumber() + "已到达仓库开始装车。");
                transportMsgParam.setTimes(DateUtil.getDateS());
                transportMsgParam.setCreateUsername(user.getName());
                transportMsgParam.setDeliverId(user.getDeliverId());
                transportMsgParam.setDeptId(user.getDeptId());
                transportMsgService.add(transportMsgParam);
            }
        }
        return ResponseData.success();
    }

    @Autowired
    private BasicCustomerService basicCustomerService;

    @Autowired
    private BasicXlbOauth2tokenService basicXlbOauth2tokenService;

    @Autowired
    private HxStorageStockService hxStorageStockService;

    @Autowired
    private HxStorageOutService hxStorageOutService;

    @Autowired
    private DictService dictService;


    @RequestMapping("/dzqcscz")
    @ResponseBody
    public ResponseData dzqcscz(TDispatchParam tDispatchParam) {
        User user = userService.getcurrentUser();
        synchronized (tDispatchParam.getId()) {
            TDispatchResult dispatchResult = tDispatchService.findBySpec(tDispatchParam, null);
            BasicCustomerParam basicCustomerParam = new BasicCustomerParam();
            basicCustomerParam.setCustomerOperateId(Integer.parseInt(dispatchResult.getOperateId().toString()));
            BasicCustomerResult cr = basicCustomerService.findBySpec(basicCustomerParam, null);

            BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
            oauth2tokenParam.setDeliverId(user.getDeliverId());
            oauth2tokenParam.setGsnumber(cr.getGsnumber());
            BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);
            if (oauth2tokenResult == null) {
                return ResponseData.error("未获取到客户对接信息，无法电子签约");
            }

            //重新修改 运单和司机的绑定关系
            String tranDriveUpdateUrl = this.hxlApiUrl + "/hxl.open.tms.signature.reset";
            JSONObject tranDriveUpdateObj = new JSONObject();
            tranDriveUpdateObj.put("source_id", dispatchResult.getId());
            tranDriveUpdateObj.put("source_system", "XIANFEI"); //来源系统 先飞为 XIANFEI,可用值:LOCAL,XIANFEI
            String tranDriveUpdateRes = HttpRequest.post(tranDriveUpdateUrl)
                    .timeout(60000)
                    .contentType("application/json;charset=UTF-8")
                    .header("Accept", "application/json")
                    .header("Authorization", "bearer " + oauth2tokenResult.getOauth2TokenXlb()).body(tranDriveUpdateObj.toString()).execute().body();
            JSONObject tranDriveUpdateObject = new JSONObject(tranDriveUpdateRes);
            if (!"0".equals(tranDriveUpdateObject.get("code").toString())) {
                String msg = tranDriveUpdateObject.get("msg").toString();
                return ResponseData.error("电子签[重置次数]错误：" + msg);
            }
        }

        return ResponseData.success();
    }

    /**
     * 离场发运
     */
    @RequestMapping("/dianziqianyue")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class, timeout = 180)
    public ResponseData dianziqianyue(TDispatchParam tDispatchParam) {
        User user = userService.getcurrentUser();
        synchronized (tDispatchParam.getId()) {
            TDispatchResult dispatchResult = tDispatchService.findBySpec(tDispatchParam, null);
            TransportMsgParam q = new TransportMsgParam();
            q.setDispatchNumber(dispatchResult.getDispatchNumber());
            q.setStatus("到仓装车");
//            TransportMsgResult dcqdByNumSpec = this.transportMsgService.findDcqdByNumSpec(q);
//            if(ToolUtil.isNotEmpty(dispatchResult.getSginKey())){
//                return ResponseData.error("已完成信息同步，请在相应司机端进行签署");
//            }
            if (ToolUtil.isEmpty(dispatchResult.getXlbDepartOrderId())) {
                return ResponseData.error("未获取到新零帮发车单号，无法电子签约");
            }
            BasicCustomerParam basicCustomerParam = new BasicCustomerParam();
            basicCustomerParam.setCustomerOperateId(Integer.parseInt(dispatchResult.getOperateId().toString()));
            BasicCustomerResult cr = basicCustomerService.findBySpec(basicCustomerParam, null);
            if (cr == null) {
                return ResponseData.error("客户信息不存在，无法电子签约");
            }
            if (ToolUtil.isEmpty(cr.getStoreIdXlb())) {
                return ResponseData.error("发货门店id未配置，无法电子签约");
            }
            if (ToolUtil.isEmpty(cr.getGsnumber())) {
                return ResponseData.error("新零帮公司号未配置，无法电子签约");
            }
            if (!"是".equals(cr.getIsEtcSign())) {
                return ResponseData.error("客户未配置【电子签收】，无法电子签约");
            }
            Map<String, String> map = new HashMap<>();
            map.put("plate_number", dispatchResult.getCarnumber());
            map.put("driver_name", dispatchResult.getSiji());
            map.put("driver_tel", dispatchResult.getSijidianhua());
            BasicPrivatecar basicPrivatecar = basicPrivatecarService.getById(dispatchResult.getCarId());
            if (basicPrivatecar == null) {
                return ResponseData.error("未获取到车辆信息，无法电子签约");
            }

            if(ToolUtil.isEmpty(basicPrivatecar.getDriver1())){
                return ResponseData.error("车辆请先绑定司机！");
            }

            //校验司机姓名，不能包含数字
            if (basicPrivatecar.getDriver1().matches(".*\\d+.*")) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                return ResponseData.error("电子签收不允许车辆绑定司机[" + basicPrivatecar.getDriver1() + "]名称包含数字！");
            }

            //判断手机号是否合法
            String pattern = "^1[3-9]\\d{9}$";
            Pattern r = Pattern.compile(pattern);
            Matcher m = r.matcher(basicPrivatecar.getTel1());
            if (!m.matches()) {
                return ResponseData.error("["+basicPrivatecar.getTel1()+"],司机手机号码不正确，请更正后重试！");
            }

            BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
            oauth2tokenParam.setDeliverId(user.getDeliverId());
            oauth2tokenParam.setGsnumber(cr.getGsnumber());
            BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);
            if (oauth2tokenResult == null) {
                return ResponseData.error("未获取到客户对接信息，无法电子签约");
            }

            //同步车辆信息
            String etcCarUrl = this.hxlApiUrl + "/hxl.open.tms.driver.sync";
            JSONObject jsonEtcCarSync = new JSONObject();
            List<Map<String, Object>> etcCarList = new ArrayList<>();
            Map<String, Object> etcCarMap = new HashMap<>();
//            Map<String, Object> etcCarTypeMap = new HashMap<>();
//            etcCarTypeMap.put("source_id", DigestUtils.md5Hex(basicPrivatecar.getPrivatecarType()));
//            etcCarTypeMap.put("name", basicPrivatecar.getPrivatecarType());
//            etcCarMap.put("car_type", etcCarTypeMap);
            List<DictResult> dictResult = dictService.findByDicttypeCode2("XLB_CAR_TYPE_ID");
            if(ToolUtil.isNotEmpty(dictResult)){
                etcCarMap.put("car_type_id", dictResult.get(0).getCode());//暂定车辆类型
            }else if("1000".equals(cr.getGsnumber())){
                etcCarMap.put("car_type_id", "100000000441");//暂定车辆类型
            }else{
                etcCarMap.put("car_type_id", "6666600000001");//暂定车辆类型
            }

            etcCarMap.put("plate_number", basicPrivatecar.getPrivatecarCarnumber());
//            etcCarMap.put("source_id", basicPrivatecar.getId());
            Long carId = IdUtil.createSnowflake(1,1).nextId();
            etcCarMap.put("source_id", carId);//你车辆的source_id. 你每次重新生成吧 20241229
            etcCarList.add(etcCarMap);
            jsonEtcCarSync.put("cars", etcCarList);
            jsonEtcCarSync.put("real_name", basicPrivatecar.getDriver1());
            jsonEtcCarSync.put("source_id", basicPrivatecar.getDriverId1());//司机的ID
            jsonEtcCarSync.put("source_system", "XIANFEI");
            jsonEtcCarSync.put("tel", basicPrivatecar.getTel1());
            jsonEtcCarSync.put("verified", true);
//            jsonEtcCarSync.put("carrier_id", "100100000046");
            if("1000".equals(cr.getGsnumber())){
                jsonEtcCarSync.put("carrier_id", "100000000383");//暂定车辆类型
            }else{
                jsonEtcCarSync.put("carrier_id", "100100000046");//暂定车辆类型
            }
            String etcCarSyncRes = HttpRequest.post(etcCarUrl)
                    .timeout(60000)
                    .contentType("application/json;charset=UTF-8")
                    .header("Accept", "application/json")
                    .header("Authorization", "bearer " + oauth2tokenResult.getOauth2TokenXlb()).body(jsonEtcCarSync.toString()).execute().body();
            JSONObject etcCarSyncObject = new JSONObject(etcCarSyncRes);
            if (!"0".equals(etcCarSyncObject.get("code").toString())) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                String msg = etcCarSyncObject.get("msg").toString();
                return ResponseData.error("电子签[同步车辆信息]错误：" + msg);
            }
            if(ToolUtil.isEmpty(dispatchResult.getSginKey())){
                //同步运单信息
                String etcSignUrl = this.hxlApiUrl + "/hxl.open.tms.transportOrder.sync";
                JSONObject jsonEtc = new JSONObject();
                jsonEtc.put("depart_order_fid", dispatchResult.getXlbDepartOrderId()); //发车单
                jsonEtc.put("driver_id", basicPrivatecar.getDriverId1()); //司机id 为来源方系统ID
                jsonEtc.put("source_id", dispatchResult.getId()); //来源系统方的ID
                jsonEtc.put("source_system", "XIANFEI"); //来源系统 先飞为 XIANFEI,可用值:LOCAL,XIANFEI
                jsonEtc.put("store_id", cr.getStoreIdXlb()); //门店id
                jsonEtc.put("store_name", cr.getCustomerName()); //门店名称
                jsonEtc.put("state", "TRANSITING"); //运输中
                jsonEtc.put("electric_sign", true); //是否电子签
                jsonEtc.put("storehouse_id", cr.getXlbStorehouseId());
                jsonEtc.put("actual_kilometers",dispatchResult.getMileageTraveled());//实际里程
                jsonEtc.put("car_id",carId);//车辆id
//                jsonEtc.put("carrier_id","100100000046");//承运商id
                if("1000".equals(cr.getGsnumber())){
                    jsonEtc.put("carrier_id", "100000000383");//暂定车辆类型
                }else{
                    jsonEtc.put("carrier_id", "100100000046");//暂定车辆类型
                }
                jsonEtc.put("carrier_name",dispatchResult.getCarrierName());//承运商名称
                jsonEtc.put("departed_time",dispatchResult.getFayunTimes());//发车时间
                jsonEtc.put("driver_name",dispatchResult.getSiji());//司机名称
                jsonEtc.put("driver_phone",dispatchResult.getSijidianhua());//司机电话
                jsonEtc.put("dispatcher",dispatchResult.getDianduyuan());//调度人
                jsonEtc.put("load_rate", dispatchResult.getFulllv());//满载率
                jsonEtc.put("memo",dispatchResult.getNotes());//备注
                jsonEtc.put("plate_number",dispatchResult.getCarnumber());//车牌号
                jsonEtc.put("volume",dispatchResult.getToovolume());//装载体积(m³)
                List<Map<String, String>> tranTsportMaps = new ArrayList<>();
                Map<String, String> mapParmTranTsport;
                BigDecimal pieceNumberSum = BigDecimal.ZERO;
                BigDecimal tooDeployNumSum = BigDecimal.ZERO;

                Integer transportNumberCnt = 0;
                List<OrderTransportResult> unitList = orderTransportService.getUnitList(dispatchResult.getDispatchNumber());
                for (OrderTransportResult obj : unitList) {
                    BigDecimal _numSum = BigDecimal.ZERO;
                    mapParmTranTsport = new HashMap<>();
                    mapParmTranTsport.put("client_id", obj.getXlbClientId());
                    mapParmTranTsport.put("client_name", obj.getGetUnit());
                    tranTsportMaps.add(mapParmTranTsport);
                    if(ToolUtil.isNotEmpty(obj.getPieceNumber())){
                        pieceNumberSum = pieceNumberSum.add(new BigDecimal(obj.getPieceNumber()));
                        _numSum = _numSum.add(new BigDecimal(obj.getPieceNumber()));
                    }
                    if(ToolUtil.isNotEmpty(obj.getTooDeployNum())){
                        tooDeployNumSum = tooDeployNumSum.add(new BigDecimal(obj.getTooDeployNum()));
                        _numSum = _numSum.add(new BigDecimal(obj.getTooDeployNum()));
                    }
                    mapParmTranTsport.put("check_quantity", _numSum.toString());//质检数量
                    mapParmTranTsport.put("pick_quantity", _numSum.toString());//拣货数量
                    mapParmTranTsport.put("pick_state", "FINISH");
                    mapParmTranTsport.put("check_state", "FINISH");

                    jsonEtc.put("storehouse_name", obj.getSetUnit());
                    transportNumberCnt = transportNumberCnt + obj.getTransportNumberCnt();
                }
                BigDecimal numSum = pieceNumberSum.add(tooDeployNumSum);
                jsonEtc.put("whole_quantity",tooDeployNumSum);//整件数量
                jsonEtc.put("open_stock_quantity",pieceNumberSum);//拆零数量
                jsonEtc.put("order_count",numSum);//订单数
                jsonEtc.put("pallet_count",transportNumberCnt);//托盘数
                jsonEtc.put("pick_item_count",numSum);//拣货数量
                jsonEtc.put("pick_quantity",numSum);//拣货数量
                jsonEtc.put("pick_state","FINISH");//拣货状态
                jsonEtc.put("quantity",numSum);//拣货数量
                jsonEtc.put("total_kilometers",dispatchResult.getMileageTraveled());//总公里数
                jsonEtc.put("weight",numSum);//拣货数量
                jsonEtc.put("transport_time",dispatchResult.getFayunTimes());//配送日期
                jsonEtc.put("departed_time",dispatchResult.getFayunTimes());//发车时间
                jsonEtc.put("dispatch_time",dispatchResult.getFayunTimes());// 调度时间
                jsonEtc.put("dispatcher",dispatchResult.getDianduyuan());//调度人

                jsonEtc.put("transport_clients", tranTsportMaps); //门店名称
                String etcSignRes = HttpRequest.post(etcSignUrl)
                        .timeout(60000)
                        .contentType("application/json;charset=UTF-8")
                        .header("Accept", "application/json")
                        .header("Authorization", "bearer " + oauth2tokenResult.getOauth2TokenXlb()).body(jsonEtc.toString()).execute().body();
                JSONObject etcSignObject = new JSONObject(etcSignRes);
                if (!"0".equals(etcSignObject.get("code").toString())) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                    String msg = etcSignObject.get("msg").toString();
                    return ResponseData.error("电子签[同步运单信息]错误：" + msg);
                }else{
                    if(ToolUtil.isNotEmpty(etcSignObject.get("data"))){
                        tDispatchService.lambdaUpdate()
                                .eq(TDispatch::getId,dispatchResult.getId())
                                .set(TDispatch::getSginKey,etcSignObject.get("data").toString())
                                .update();
                    }
                }
            }

            //重新修改 运单和司机的绑定关系
            String tranDriveUpdateUrl = this.hxlApiUrl + "/hxl.open.tms.transportOrder.update.driver";
            JSONObject tranDriveUpdateObj = new JSONObject();
            tranDriveUpdateObj.put("source_driver_id", basicPrivatecar.getDriverId1());
            tranDriveUpdateObj.put("source_id", dispatchResult.getId());
            tranDriveUpdateObj.put("source_system", "XIANFEI"); //来源系统 先飞为 XIANFEI,可用值:LOCAL,XIANFEI
            String tranDriveUpdateRes = HttpRequest.post(tranDriveUpdateUrl)
                    .timeout(60000)
                    .contentType("application/json;charset=UTF-8")
                    .header("Accept", "application/json")
                    .header("Authorization", "bearer " + oauth2tokenResult.getOauth2TokenXlb()).body(tranDriveUpdateObj.toString()).execute().body();
            JSONObject tranDriveUpdateObject = new JSONObject(tranDriveUpdateRes);
            if (!"0".equals(tranDriveUpdateObject.get("code").toString())) {
                String msg = tranDriveUpdateObject.get("msg").toString();
                return ResponseData.error("电子签[更改运单司机信息]错误：" + msg);
            }
            //生成电子签约
            String etcSignGenUrl = this.hxlApiUrl + "/hxl.open.tms.signature.generate";
            JSONObject jsonEtcGen = new JSONObject();
            jsonEtcGen.put("depart_fid", dispatchResult.getXlbDepartOrderId());
            jsonEtcGen.put("store_id", cr.getStoreIdXlb());
            String etcSignGenRes = HttpRequest.post(etcSignGenUrl)
                    .timeout(360000)
                    .contentType("application/json;charset=UTF-8")
                    .header("Accept", "application/json")
                    .header("Authorization", "bearer " + oauth2tokenResult.getOauth2TokenXlb()).body(jsonEtcGen.toString()).execute().body();
            JSONObject etcSignGenObject = new JSONObject(etcSignGenRes);
            if (!"0".equals(etcSignGenObject.get("code").toString())) {
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                String msg = etcSignGenObject.get("msg").toString();
                return ResponseData.error("电子签[生成电子签约]错误：" + msg);
            }
        }
        return ResponseData.success();
    }

    /**
     * 离场发运
     */
    @RequestMapping("/editlicahng")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class, timeout = 180)
    public ResponseData editlicahng(TDispatchParam tDispatchParam) {
        User user = userService.getcurrentUser();
        synchronized (tDispatchParam.getId()) {
            TDispatchResult dispatchResult = tDispatchService.findBySpec(tDispatchParam, null);
            if (dispatchResult != null) {
                if (dispatchResult.getTstate().equals("待发运")) {
                    BasicCustomerParam basicCustomerParam = new BasicCustomerParam();
                    basicCustomerParam.setCustomerOperateId(Integer.parseInt(dispatchResult.getOperateId().toString()));
                    BasicCustomerResult cr = basicCustomerService.findBySpec(basicCustomerParam, null);
                    if (cr != null) {
                        List<TrayNumberVo> trayNumbers = new ArrayList<>();
                        OrderTransportParam orderTransportParam = new OrderTransportParam();
                        orderTransportParam.setDeptId(user.getDeptId());
                        List<OrderTransportResult> list = this.orderTransportService.findListBySpecNewsss(orderTransportParam, dispatchResult.getDispatchNumber(), user.getOperateId());
                        for (OrderTransportResult tr : list) {//截取托盘
                            if (ToolUtil.isNotEmpty(tr.getStockPort())) {
                                int indexOfChar = tr.getCustomerOrder().indexOf("_"); // 获取第一次出现"_"的索引位置
                                if (indexOfChar != -1) {
                                    String result = tr.getCustomerOrder().substring(0, indexOfChar); // 从开头到"o"之间的子字符串
                                    trayNumbers.add(TrayNumberVo.builder()
                                            .result(result)
                                            .stockPort(tr.getStockPort())
                                            .build());
                                }
                            }
                            //清空巷道
                            if (ToolUtil.isNotEmpty(cr.getAgvRobot()) && cr.getAgvRobot().equals("2")) {
                                if (ToolUtil.isNotEmpty(cr.getAgvBaseUrl())) {
                                    try{
                                        String stok = tr.getStockPort().replaceAll("通道", "");
                                        FeedbackTaskRS res = TustApiUtils.clear(cr.getAgvBaseUrl(), "H" + StringUtils.leftPad(stok, 3, "0"));
                                    }catch (Exception e){
                                        e.printStackTrace();
                                    }
                                }
                            } else if (ToolUtil.isNotEmpty(cr.getAgvRobot()) && cr.getAgvRobot().equals("1")) {
                                if (ToolUtil.isNotEmpty(cr.getAgvBaseUrl())) {
                                    String stok = tr.getStockPort().replaceAll("通道", "");
                                    stok = StringUtils.stripStart(stok, "0");
                                    try{
                                        if (cr.getId() == 48) { // 齐河
                                            //清空巷道
                                            this.hikAgvTaskService.clear2(stok);
                                        } else {
                                            HikRsVo hikRsVo = HikApiUtils.clearRoadWay(cr.getAgvBaseUrl(), stok);
                                        }
                                    }catch (Exception e){
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                        if (ToolUtil.isNotEmpty(cr.getModeTms())) {
                            if (cr.getModeTms().equals("1") || cr.getModeTms().equals("3") || cr.getModeTms().equals("4")) {
                                for (OrderTransportResult r : list) {
                                    if (ToolUtil.isNotEmpty(r.getOrderNumber())) {
                                        HxStorageStockParam stockParamdelete = new HxStorageStockParam();
                                        stockParamdelete.setStockState("集货");
                                        stockParamdelete.setStorageNumber(r.getOrderNumber());
                                        hxStorageStockService.deleteBySpec(stockParamdelete);//删除集货区库存

                                        hxStorageOutService.lambdaUpdate()
                                                .eq(HxStorageOut::getStorageNumber, r.getOrderNumber())
                                                .set(HxStorageOut::getStartState, "已发车")
                                                .update();//更新零售拣货任务 发车状态
                                    }

                                }
                                //清理对应的集货中心
                                for (TrayNumberVo t : trayNumbers) {
                                    if(ToolUtil.isNotEmpty(t.getResult())){
                                        hxCollectionLocationService.lambdaUpdate()
                                                .eq(HxCollectionLocation::getTrayNumber, t.getResult())
                                                .set(HxCollectionLocation::getStatus, null)
                                                .set(HxCollectionLocation::getGetUnit, null)
                                                .set(HxCollectionLocation::getGetUnitId, null)
                                                .set(HxCollectionLocation::getTrayNumber, null)
                                                .update();
                                    }
                                }
                            }
                        }
                        if (ToolUtil.isNotEmpty(cr.getGsnumber()) && ToolUtil.isNotEmpty(cr.getStoreIdXlb())) {
                            BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
                            oauth2tokenParam.setDeliverId(user.getDeliverId());
                            oauth2tokenParam.setGsnumber(cr.getGsnumber());
                            BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);
                            if (oauth2tokenResult != null) {
                                if (ToolUtil.isNotEmpty(oauth2tokenResult.getOauth2TokenXlb())) {
                                    if (list.size() > 0) {
                                        if (ToolUtil.isNotEmpty(cr.getModeTms()) && cr.getModeTms().equals("2")) {
                                            List<String> pick_order_ids = new ArrayList<String>();
                                            for (OrderTransportResult r : list) {
                                                if (ToolUtil.isNotEmpty(r.getOrderNumber())) {
                                                    pick_order_ids.add(r.getOrderNumber());
                                                }
                                            }
                                            if (pick_order_ids.size() > 0) {
                                                String url = this.hxlApiUrl + "/hxl.open.wms.depart";
//        										String url = "https://hxl-api.xlbsoft.com/api/hxl.open.wms.depart";
                                                Map<String, String> map = new HashMap<>();
                                                map.put("plate_number", dispatchResult.getCarnumber());
                                                map.put("driver_name", dispatchResult.getSiji());
                                                map.put("driver_tel", dispatchResult.getSijidianhua());
                                                BigDecimal yibai = new BigDecimal("100");
                                                BasicPrivatecar basicPrivatecar = basicPrivatecarService.getById(dispatchResult.getCarId());
                                                if (ToolUtil.isNotEmpty(basicPrivatecar.getPrivatecarCarlong())) {
                                                    BigDecimal privatecarCarlong = new BigDecimal(basicPrivatecar.getPrivatecarCarlong());
                                                    BigDecimal privatecarCarlongmul = privatecarCarlong.multiply(yibai).setScale(2, BigDecimal.ROUND_HALF_DOWN);
                                                    map.put("length", privatecarCarlongmul + "");
                                                }
                                                if (ToolUtil.isNotEmpty(basicPrivatecar.getPrivatecarCarwide())) {
                                                    BigDecimal privatecarCarwide = new BigDecimal(basicPrivatecar.getPrivatecarCarwide());
                                                    BigDecimal privatecarCarwidemul = privatecarCarwide.multiply(yibai).setScale(2, BigDecimal.ROUND_HALF_DOWN);
                                                    map.put("width", privatecarCarwidemul + "");
                                                }
                                                if (ToolUtil.isNotEmpty(basicPrivatecar.getPrivatecarCarhigh())) {
                                                    BigDecimal privatecarCarhigh = new BigDecimal(basicPrivatecar.getPrivatecarCarhigh());
                                                    BigDecimal privatecarCarhighmul = privatecarCarhigh.multiply(yibai).setScale(2, BigDecimal.ROUND_HALF_DOWN);
                                                    map.put("height", privatecarCarhighmul + "");
                                                }
                                                JSONObject json = new JSONObject();
                                                json.put("store_id", cr.getStoreIdXlb());
                                                json.put("pick_order_fids", pick_order_ids);
                                                json.put("car", map);
                                                if (ToolUtil.isNotEmpty(cr.getNeedCheck())) {
                                                    if (cr.getNeedCheck().equals("1")) {
                                                        json.put("need_check", "true");
                                                    } else {
                                                        json.put("need_check", "false");
                                                    }
                                                }
                                                json.put("operator", dispatchResult.getSiji());
                                                String post = HttpRequest.post(url)
                                                        .timeout(60000)
                                                        .header("Authorization", "bearer " + oauth2tokenResult.getOauth2TokenXlb()).body(json.toString()).execute().body();
//        	    							System.out.println("================json："+json+"========================");
//        	    							System.out.println("================post："+post+"========================");
                                                JSONObject jsonObject = new JSONObject(post);
                                                if (jsonObject.get("code").toString().equals("0")) {
                                                    String depart_order_id = jsonObject.get("data").toString();
                                                    if (ToolUtil.isNotEmpty(depart_order_id)) {
                                                        tDispatchParam.setXlbDepartOrderId(depart_order_id);
                                                    } else {
                                                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                                                        return ResponseData.error("发车单id为空");
                                                    }
                                                } else {
                                                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                                                    String msg = jsonObject.get("msg").toString();
        											return ResponseData.error(msg);
                                                }
                                            }
                                        }
//                                        if (ToolUtil.isNotEmpty(cr.getModeTms()) && cr.getModeTms().equals("3")) {
////        									String url = "https://test-api.xlbsoft.com/api/hxl.open.wms.depart.create";
//                                            String url = this.hxlApiUrl + "/hxl.open.wms.depart.create";
//                                            String trayCode = getOperateIdOrderPrefix(user);
//                                            JSONArray jsonArray2 = new JSONArray();
//                                            OrderTransportParam orderTransportParam2 = new OrderTransportParam();
//                                            orderTransportParam2.setOrderNumber(dispatchResult.getDispatchNumber());
//                                            List<OrderTransportResult> list2 = this.orderTransportService.carDetailsSingleToo3(orderTransportParam2);
//                                            if (list2.size() > 0) {
//                                                List<OrderTransportResult> dblist = orderTransportService.findPieceNumberNumBySpec(dispatchResult.getDispatchNumber());
//                                                for (OrderTransportResult r : list2) {
//                                                    JSONArray jsonArray = new JSONArray();
//                                                    TransportDispatchParam transportDispatchParam = new TransportDispatchParam();
//                                                    transportDispatchParam.setDispatchNumber(dispatchResult.getDispatchNumber());
//                                                    transportDispatchParam.setGetLocationId(r.getGetLocationId());
//                                                    List<TransportDispatchResult> dlist = transportDispatchService.findSumGoodsBySpec(transportDispatchParam);
//                                                    for (TransportDispatchResult dr : dlist) {
//                                                        JSONObject jsonObject = new JSONObject();
//                                                        jsonObject.put("basic_quantity", dr.getJibenNum());
//                                                        jsonObject.put("basic_unit", dr.getJibenUnit());
//                                                        if (ToolUtil.isNotEmpty(dr.getDemolition())) {
//                                                            jsonObject.put("box_code", trayCode + "FX" + cn.stylefeng.guns.core.util.DateUtil.getDatesBch() + DateUtil.getRandomNumber());
//                                                        }
//                                                        if (ToolUtil.isNotEmpty(dr.getDaoqiDate())) {
//                                                            jsonObject.put("expire_date", dr.getDaoqiDate() + " 00:00:00");
//                                                        }
//                                                        jsonObject.put("item_bar_code", dr.getGoodsPcode69());
//                                                        jsonObject.put("item_code", dr.getGoodsNumber());
//                                                        jsonObject.put("item_id", dr.getXlbGoodsId());
//                                                        jsonObject.put("item_name", dr.getGoodsName());
//                                                        jsonObject.put("item_spec", dr.getGoodsSpecs());
//                                                        if (ToolUtil.isNotEmpty(dr.getDetailedDate())) {
//                                                            jsonObject.put("producing_date", dr.getDetailedDate() + " 00:00:00");
//                                                        }
//                                                        jsonObject.put("quantity", dr.getTooDeployNum());
//                                                        jsonObject.put("ratio", dr.getRate());
//                                                        jsonObject.put("storage_id", dr.getXlbPositionId());
//                                                        jsonObject.put("storage_name", dr.getPositionNumber());
//                                                        jsonObject.put("unit", dr.getGoodsUnit());
//                                                        jsonArray.put(jsonObject);
//                                                    }
//                                                    JSONObject jsonObject2 = new JSONObject();
//                                                    TransportDispatchResult resultzjclunit = transportDispatchService.findClZjunitSumBySpec(dispatchResult.getDispatchNumber(), r.getGetLocationId());
//                                                    if (resultzjclunit != null) {
//                                                        jsonObject2.put("quantity", resultzjclunit.getZjsum());
////        												jsonObject2.put("demolition_item_quantity", resultzjclunit.getClsum().replaceAll("\\..*",""));
//                                                        jsonObject2.put("volume", resultzjclunit.getTooDeployVolume());
//                                                    }
//                                                    BigDecimal dbNumSum = new BigDecimal("0");
//                                                    for (OrderTransportResult dbr : dblist) {
//                                                        if (dbr.getGetLocationId().equals(r.getGetLocationId())) {
//                                                            BigDecimal dbNum = new BigDecimal(dbr.getDbSum());
//                                                            dbNumSum = dbNumSum.add(dbNum);
//                                                        }
//                                                    }
//                                                    jsonObject2.put("demolition_item_quantity", (dbNumSum + "").replaceAll("\\..*", ""));
//                                                    jsonObject2.put("dump_quantity", "0");
//                                                    jsonObject2.put("client_id", r.getXlbClientId());
//                                                    jsonObject2.put("client_name", r.getGetUnit());
//                                                    jsonObject2.put("details", jsonArray);
//                                                    jsonObject2.put("order_fid", r.getLmAssociationOrder());
//                                                    if (ToolUtil.isNotEmpty(r.getLmOrderType())) {
//                                                        if (r.getLmOrderType().equals("门店调出")) {
//                                                            jsonObject2.put("order_type", "STORE_OUT");
//                                                        }
//                                                        if (r.getLmOrderType().equals("采购退货")) {
//                                                            jsonObject2.put("order_type", "RETURN");
//                                                        }
//                                                        if (r.getLmOrderType().equals("批发销售")) {
//                                                            jsonObject2.put("order_type", "WHOLESALE");
//                                                        }
//                                                        if (r.getLmOrderType().equals("调整出库")) {
//                                                            jsonObject2.put("order_type", "ADJUST_OUT");
//                                                        }
//                                                        if (r.getLmOrderType().equals("仓间调拨")) {
//                                                            jsonObject2.put("order_type", "TRANSFER");
//                                                        }
//                                                    }
//                                                    jsonArray2.put(jsonObject2);
//                                                }
//
//                                                JSONObject json = new JSONObject();
//                                                TransportDispatchResult resultzjcl = transportDispatchService.findClZjSumBySpec(dispatchResult.getDispatchNumber());
//                                                if (resultzjcl != null) {
//                                                    json.put("quantity", resultzjcl.getZjsum());
////            										json.put("demolition_item_quantity", resultzjcl.getClsum().replaceAll("\\..*",""));
//                                                }
//                                                BigDecimal dbNumSum = new BigDecimal("0");
//                                                for (OrderTransportResult dbr : dblist) {
//                                                    BigDecimal dbNum = new BigDecimal(dbr.getDbSum());
//                                                    dbNumSum = dbNumSum.add(dbNum);
//                                                }
//                                                json.put("demolition_item_quantity", (dbNumSum + "").replaceAll("\\..*", ""));
//                                                json.put("dump_quantity", "0");
//                                                json.put("volume", dispatchResult.getToovolume());
//                                                json.put("delivery_date", dispatchResult.getStartDate());
//                                                json.put("client_count", list2.size());
//                                                json.put("details", jsonArray2);
//                                                json.put("driver_name", dispatchResult.getSiji());
//                                                json.put("driver_phone", dispatchResult.getSijidianhua());
//                                                json.put("number", dispatchResult.getCarnumber());
//                                                json.put("store_id", list2.get(0).getXlbSetUnitId());
//                                                json.put("store_name", list2.get(0).getSetUnit());
//                                                json.put("storehouse_id", list2.get(0).getXlbSetWarehouseId());
//                                                json.put("storehouse_name", list2.get(0).getXlbSetWarehouse());
//                                                json.put("operator", user.getName());
//                                                json.put("wms_fid", dispatchResult.getDispatchNumber());
//                                                String post = HttpRequest.post(url)
//                                                        .timeout(120000)
//                                                        .header("Authorization", "bearer " + oauth2tokenResult.getOauth2TokenXlb()).body(json.toString()).execute().body();
////	    	    							System.out.println("================json："+json+"========================");
////	    	    							System.out.println("================post："+post+"========================");
//                                                JSONObject jsonObject = new JSONObject(post);
//                                                if (jsonObject.get("code").toString().equals("0")) {
//                                                    String depart_order_id = jsonObject.get("data").toString();
//                                                    if (ToolUtil.isNotEmpty(depart_order_id)) {
//                                                        tDispatchParam.setXlbDepartOrderId(depart_order_id);
//                                                    } else {
//                                                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
//                                                        return ResponseData.error("发车单id为空");
//                                                    }
//                                                } else {
//                                                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
//                                                    String msg = jsonObject.get("msg").toString();
//                                                    return ResponseData.error(msg);
//                                                }
//                                            }
//                                        }
                                    }
                                }
                            }
                        }
                        tDispatchParam.setFayunTimes(DateUtil.getDateS());
                        tDispatchParam.setTstate("运输中");
                        this.tDispatchService.update(tDispatchParam);

                        TransportMsgParam transportMsgParam = new TransportMsgParam();
                        transportMsgParam.setDispatchNumber(dispatchResult.getDispatchNumber());
                        transportMsgParam.setStatus("离场发运");
                        transportMsgParam.setMsgType("系统");
                        transportMsgParam.setContent("车辆已经离开发货地，运单正在运输中。");
                        transportMsgParam.setTimes(DateUtil.getDateS());
                        transportMsgParam.setCreateUsername(user.getName());
                        transportMsgParam.setDeliverId(user.getDeliverId());
                        transportMsgParam.setDeptId(user.getDeptId());
                        transportMsgParam.setV2(user.getPhone());
                        transportMsgService.add(transportMsgParam);

                        TransportMsgParam dcqd = new TransportMsgParam();
                        dcqd.setV3(dispatchResult.getCarId() + "");
                        dcqd.setDeptId(user.getDeptId());
                        dcqd.setStatus("到仓签到");
                        TransportMsgResult msgResult = transportMsgService.findDcqdBySpec(dcqd, user.getOperateId());
                        if (msgResult != null) {
                            TransportMsgParam msgParam = new TransportMsgParam();
                            msgParam.setId(msgResult.getId());
                            msgParam.setV4("已发运");
                            transportMsgService.update(msgParam);
                        }


//                        Map<String, String> ttMap = new HashMap<>();
//        				for (TrayNumberVo t : trayNumbers) {
//        					boolean update = hxCollectionLocationService.lambdaUpdate()
//        							.eq(HxCollectionLocation::getTrayNumber, t.getResult())
//        							.set(HxCollectionLocation::getStatus, null)
//        							.set(HxCollectionLocation::getGetUnit, null)
//        							.set(HxCollectionLocation::getGetUnitId, null)
//        							.set(HxCollectionLocation::getTrayNumber, null)
//        							.update();
//
//        					if(update){
//        						if(ttMap.get(t.getStockPort()) == null){
//        							if(ToolUtil.isNotEmpty(cr.getAgvRobot())&&cr.getAgvRobot().equals("2")) {
//        								if(ToolUtil.isNotEmpty(cr.getAgvBaseUrl())) {
//        									String stok = t.getStockPort().replaceAll("通道", "");
//        									FeedbackTaskRS res = TustApiUtils.clear(cr.getAgvBaseUrl(), "H"+ StringUtils.leftPad(stok,3,"0"));
//        									if(res != null && res.getCode() == 200){
//        										ttMap.put(t.getStockPort(),t.getStockPort());
//        									}
//        								}
//        							} else if(ToolUtil.isNotEmpty(cr.getAgvRobot()) && cr.getAgvRobot().equals("1") ) {
//                                        if(ToolUtil.isNotEmpty(cr.getAgvBaseUrl())) {
//                                            String stok = t.getStockPort().replaceAll("通道", "");
//                                            HikRsVo hikRsVo = HikApiUtils.clearRoadWay(cr.getAgvBaseUrl(), stok);
//                                            if(hikRsVo != null && "0".equals(hikRsVo.getCode())){
//                                                ttMap.put(t.getStockPort(),t.getStockPort());
//                                            }
//                                        }
//                                    }
//        						}
//
//        					}
//        				}
                    }
                }
            }
        }
        return ResponseData.success();
    }

    /**
     * 获取所属项目单号前缀
     *
     * @param user
     * @return
     */
    public String getOperateIdOrderPrefix(User user) {
        if (user.getOperateId() != null) {
            Dept dept = new Dept();
            dept.setOperateId(user.getOperateId());
            Dept resdept = deptService.findBySpec(dept);
            if (resdept != null) {
                if (ToolUtil.isNotEmpty(resdept.getOrderPrefix())) {
                    return resdept.getOrderPrefix();
                } else {
                    return user.getAccount().substring(0, 3);
                }
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    @Value("${tusk.baseUrl}")
    private String tuskBaseUrl;

    @Value("${hik.baseUrl}")
    private String hikBaseUrl;

    @Autowired
    private DeptService deptService;

    @Autowired
    private HxCollectionLocationService hxCollectionLocationService;

    public static void main(String[] args) {
        String aa = "001通道";
        aa = aa.replaceAll("通道", "");
        if (aa.substring(0, 1).equals("0")) {
            aa = aa.substring(1);
        }
        if (aa.substring(0, 1).equals("0")) {
            aa = aa.substring(1);
        }
        //System.out.println(aa); // 输出结果为 "Hell"
    }

    /**
     * 送达
     */
    @RequestMapping("/editsongda")
    @ResponseBody
    public ResponseData editsongda(TransportReceiptParam transportReceiptParam) {
        User user = userService.getcurrentUser();

        TDispatchParam tDispatchParam = new TDispatchParam();
        tDispatchParam.setDispatchNumber(transportReceiptParam.getDispatchNumber());
        TDispatchResult dispatchResult = tDispatchService.findBySpec(tDispatchParam, null);
        if (ToolUtil.isNotEmpty(dispatchResult.getXlbDepartOrderId())) {
            return ResponseData.error("请用司机账号操作送达并上传电子签名");
        }

        transportReceiptParam.setSdtime(DateUtil.getDateS());
        transportReceiptParam.setSdtstate("已送达");
        transportReceiptParam.setSdusername(user.getName());
        transportReceiptService.update(transportReceiptParam);

        TransportMsgParam transportMsgParam = new TransportMsgParam();
        transportMsgParam.setDispatchNumber(transportReceiptParam.getDispatchNumber());
        transportMsgParam.setStatus("送达");
        transportMsgParam.setMsgType("系统");
        transportMsgParam.setContent(transportReceiptParam.getGetUnit() + transportReceiptParam.getGetLocation() + "已确认送达。");
        transportMsgParam.setTimes(DateUtil.getDateS());
        transportMsgParam.setCreateUsername(user.getName());
        transportMsgParam.setDeliverId(user.getDeliverId());
        transportMsgParam.setDeptId(user.getDeptId());
        transportMsgParam.setV1(transportReceiptParam.getGetLocationid() + "");
        transportMsgParam.setV2(transportReceiptParam.getGetUnit());
        transportMsgParam.setV3(transportReceiptParam.getGetUnitid() + "");
        transportMsgService.add(transportMsgParam);
        return ResponseData.success();
    }

    /**
     * 签收上传回传单
     *
     * @param transportReceiptParam
     * @return
     */
    @RequestMapping("/uploads")
    @ResponseBody
    public ResponseData uploads(TransportReceiptParam transportReceiptParam) {
        TransportReceipt transportReceipt = transportReceiptService.getById(transportReceiptParam.getId());
        User user = userService.getcurrentUser();

        if (ToolUtil.isNotEmpty(transportReceiptParam.getFileId())) {
            transportReceiptParam.setTime(DateUtil.getDateS());
            transportReceiptParam.setUsername(user.getName());
            transportReceiptParam.setTstate("已回传");
            transportReceiptService.update(transportReceiptParam);
        }

        TransportMsgParam transportMsgParam = new TransportMsgParam();
        transportMsgParam.setStatus("客户签收");
        transportMsgParam.setDispatchNumber(transportReceipt.getDispatchNumber());
        transportMsgParam.setV1(transportReceipt.getGetLocationid().toString());
        TransportMsgResult transportMsgResult = transportMsgService.findBySpec(transportMsgParam);
        if (transportMsgResult != null) {
            transportMsgParam.setMsgType("系统");
            if (ToolUtil.isNotEmpty(transportReceiptParam.getFileId())) {
                transportMsgParam.setContent(user.getName() + "签收并上传了回单，单位为：" + transportReceipt.getGetUnit());
            } else {
                transportMsgParam.setContent(user.getName() + "确认签收，单位为：" + transportReceipt.getGetUnit());
            }
            transportMsgParam.setTimes(DateUtil.getDateS());
            transportMsgParam.setCreateUsername(user.getName());
            transportMsgParam.setDeliverId(user.getDeliverId());
            transportMsgParam.setDeptId(user.getDeptId());
            transportMsgParam.setV4(transportReceiptParam.getFileId());
            transportMsgParam.setId(transportMsgResult.getId());
            transportMsgService.update(transportMsgParam);
        } else {
            transportMsgParam.setMsgType("系统");
            if (ToolUtil.isNotEmpty(transportReceiptParam.getFileId())) {
                transportMsgParam.setContent(user.getName() + "签收并上传了回单，单位为：" + transportReceipt.getGetUnit());
            } else {
                transportMsgParam.setContent(user.getName() + "确认签收，单位为：" + transportReceipt.getGetUnit());
            }
            transportMsgParam.setTimes(DateUtil.getDateS());
            transportMsgParam.setCreateUsername(user.getName());
            transportMsgParam.setDeliverId(user.getDeliverId());
            transportMsgParam.setDeptId(user.getDeptId());
            transportMsgParam.setV2(transportReceipt.getGetUnit());
            transportMsgParam.setV3(transportReceipt.getGetUnitid().toString());
            transportMsgParam.setV4(transportReceiptParam.getFileId());
            transportMsgService.add(transportMsgParam);
        }
        return ResponseData.success(transportMsgService.findBySpec(transportMsgParam));
    }

    @Autowired
    private OrderTransportService orderTransportService;

    @Autowired
    private BasicPrivatecarService basicPrivatecarService;
    @Autowired
    private HikAgvTaskService hikAgvTaskService;


    /**
     * 完成
     */
    @RequestMapping("/accomplishUnitGoods")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class, timeout = 60)
    public ResponseData accomplishUnitGoods(TDispatchParam tDispatchParam) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        TDispatch tDispatch = tDispatchService.getById(tDispatchParam.getId());
        if (tDispatch == null) {
            return ResponseData.success();
        }
        //更新运输单
        tDispatchParam.setId(tDispatchParam.getId());
        tDispatchParam.setCompleteName(user.getName());
        tDispatchParam.setCompleteTimes(DateUtil.getDateS());
        tDispatchParam.setTstate("已完成");
        tDispatchService.update(tDispatchParam);

        //更新派车明细中 换算数量
//		TransportDispatchParam hsParam = new TransportDispatchParam();
//		hsParam.setDispatchNumber(tDispatch.getDispatchNumber());
//		List<TransportDispatchResult> hslist = transportDispatchService.findListBySpecXianggui(hsParam);
//		for (TransportDispatchResult i : hslist) {
//			try {
//				BigDecimal tooDeployNum = new BigDecimal(i.getTooDeployNum());
//				BigDecimal xianggui = new BigDecimal(i.getXianggui());
//				BigDecimal matrixingNumber = tooDeployNum.divide(xianggui, 2, BigDecimal.ROUND_HALF_DOWN);
//				TransportDispatchParam update = new TransportDispatchParam();
//				update.setId(i.getId());
//				update.setMatrixingNumber(matrixingNumber.toString());
//				transportDispatchService.update(update);
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}

        //更新货运订单
        TransportDispatchParam transportDispatchParam = new TransportDispatchParam();
        transportDispatchParam.setDispatchNumber(tDispatch.getDispatchNumber());
        List<TransportDispatchResult> tdrlist = transportDispatchService.findOrderListBySpec(transportDispatchParam, "已发运", null);//查询所有货运订单
        for (TransportDispatchResult dr : tdrlist) {
            TransportDispatchParam transportDispatchParam2 = new TransportDispatchParam();
            transportDispatchParam2.setTransportNumber(dr.getTransportNumber());
            transportDispatchParam2.setDispatchNumber(tDispatch.getDispatchNumber());
            List<TransportDispatchResult> tdrlist2 = transportDispatchService.findNotByCarnumber(transportDispatchParam2);//查询货运订单是否有别的派车单
            if (tdrlist2.size() == 0) {
                orderTransportService.lambdaUpdate()
                        .eq(OrderTransport::getTransportNumber, dr.getTransportNumber())
                        .set(OrderTransport::getTstate, "已完成")
                        .update();
            }
        }

        //修改车辆
        BasicPrivatecar bpcr = basicPrivatecarService.getById(tDispatch.getCarId());
        TDispatchParam tDispatchParamf = new TDispatchParam();
        tDispatchParamf.setCarId(tDispatch.getCarId());
        tDispatchParamf.setDispatchNumber(tDispatchParam.getDispatchNumber());
        TDispatchResult tDispatchResultf = tDispatchService.findByYunshuCar(tDispatchParamf, null);
        if (tDispatchResultf == null) {//如果该车没有别的派车单
            if (bpcr != null) {
                BasicPrivatecarParam bpcp = new BasicPrivatecarParam();
                bpcp.setId(bpcr.getId());
                bpcp.setPrivatecarState("空闲");
                basicPrivatecarService.update(bpcp);
            }
        }

        TransportMsgParam transportMsgParam = new TransportMsgParam();
        transportMsgParam.setStatus("配送完成");
        transportMsgParam.setDispatchNumber(tDispatch.getDispatchNumber());
        transportMsgParam.setMsgType("系统");
        transportMsgParam.setContent(user.getName() + "确认配送完成。");
        transportMsgParam.setTimes(DateUtil.getDateS());
        transportMsgParam.setCreateUsername(user.getName());
        transportMsgParam.setDeliverId(user.getDeliverId());
        transportMsgParam.setDeptId(user.getDeptId());
        transportMsgService.add(transportMsgParam);
        return ResponseData.success();
    }

    /**
     * 打印送货单
     */
    @RequestMapping("print")
    public String print() {
        return PREFIX + "/print.html";
    }

    /**
     * 打印托运单
     */
    @RequestMapping("printTy")
    public String printTy() {
        return PREFIX + "/printTy.html";
    }

    /**
     * 查询 送货单明细
     */
    @ResponseBody
    @RequestMapping("/printlist")
    public ResponseData printlist(TransportDispatchParam transportDispatchParam, TransportReceiptParam transportReceiptParam) {
        return ResponseData.success(this.transportDispatchService.findPrintlistSpec(transportDispatchParam, transportReceiptParam));
    }

    /**
     * 查询 托运单配送信息
     */
    @ResponseBody
    @RequestMapping("/getPrintReceipt")
    public TransportReceiptResult getPrintReceipt(TransportReceiptParam transportReceiptParam) {
        User user = userService.getcurrentUser();
        TransportReceiptResult receiptResult = this.transportReceiptService.getPrintReceipt(transportReceiptParam);
        if (receiptResult != null) {
            receiptResult.setZhidanren(user.getName());
        }
        return receiptResult;
    }

    /**
     * 查询 托运单明细
     */
    @ResponseBody
    @RequestMapping("/getprintlist")
    public List<TransportDispatchResult> getprintlist(TransportReceiptParam transportReceiptParam) {
        List<TransportDispatchResult> list = transportDispatchService.findPrintlistBySpec(transportReceiptParam);

        List<TransportDispatchResult> list2 = new ArrayList<TransportDispatchResult>();
        List<TransportDispatchResult> list3 = new ArrayList<TransportDispatchResult>();
        String customerOrder = "";
        for (int i = 0; i < list.size(); i++) {
            if (ToolUtil.isNotEmpty(customerOrder)) {
                if (!customerOrder.equals(list.get(i).getCustomerOrder())) {
                    TransportDispatchResult r = new TransportDispatchResult();
                    r.setListd(list3);
                    list2.add(r);
                    list3 = new ArrayList<TransportDispatchResult>();
                    list3.add(list.get(i));
                    customerOrder = list.get(i).getCustomerOrder();
                } else {
                    customerOrder = list.get(i).getCustomerOrder();
                    list3.add(list.get(i));
                    if (list3.size() == 10) {
                        TransportDispatchResult r = new TransportDispatchResult();
                        r.setListd(list3);
                        list2.add(r);
                        list3 = new ArrayList<TransportDispatchResult>();
                    }
                }
            } else {
                list3.add(list.get(i));
                customerOrder = list.get(i).getCustomerOrder();
            }
        }
        if (list3.size() > 0) {
            TransportDispatchResult r = new TransportDispatchResult();
            r.setListd(list3);
            list2.add(r);
        }
        return list2;
    }

    /**
     * 新增页面
     */
    @RequestMapping("/add")
    public String add() {
        return PREFIX + "/tDispatch_add.html";
    }

    /**
     * 编辑页面
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/tDispatch_edit.html";
    }

    /**
     * 新增接口
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(TDispatchParam tDispatchParam) {
        this.tDispatchService.add(tDispatchParam);
        return ResponseData.success();
    }

    @Autowired
    private StorageOutService storageOutService;

    @Autowired
    private TransportStevedoreSigninService transportStevedoreSigninService;

    /**
     * 编辑接口
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(TDispatchParam tDispatchParam, String[] loadingNumbers) {
        User user = userService.getcurrentUser();
        TDispatch detail = this.tDispatchService.getById(tDispatchParam.getId());
        if (tDispatchParam.getLoadingType().equals("自装")) {
            tDispatchParam.setLoadingPersonnel("自装");
        } else if (tDispatchParam.getLoadingType().equals("仓库")) {
            if (loadingNumbers != null) {
                String sloadingPersonnel = "";
                String loadingNumbersp = "";
                for (int i = 0; i < loadingNumbers.length; i++) {
                    String loadingNumber = loadingNumbers[i];
                    if (ToolUtil.isNotEmpty(loadingNumber)) {
                        TransportStevedoreSigninParam stevedoreSigninParam = new TransportStevedoreSigninParam();
                        stevedoreSigninParam.setAuditBy(loadingNumber);
                        stevedoreSigninParam.setDeptId(user.getDeptId());
                        TransportStevedoreSigninResult signres = transportStevedoreSigninService.findBySpec(stevedoreSigninParam, user.getOperateId());
                        if (signres != null) {
                            sloadingPersonnel += signres.getAuditTime();
                            loadingNumbersp += loadingNumber;
                            if (loadingNumbers.length != i + 1) {
                                sloadingPersonnel += "+";
                                loadingNumbersp += ",";
                            }
                        }
                    }
                }
                tDispatchParam.setLoadingNumber(loadingNumbersp);
                tDispatchParam.setLoadingPersonnel(sloadingPersonnel);
            }
        }
        if (tDispatchParam.getCarId().longValue() != detail.getCarId().longValue()) {
            BasicPrivatecar basicPrivatecar = basicPrivatecarService.getById(tDispatchParam.getCarId());
            tDispatchParam.setCarnumber(basicPrivatecar.getPrivatecarCarnumber());
            //修改拣货单 车牌号
            String storageOutNumbers = detail.getCustomerOrder();
            String[] strs = storageOutNumbers.split(";");
            for (String str : strs) {
                StorageOutParam sop = new StorageOutParam();
                sop.setStorageOutNumber(str);
                sop.setOutOrderStatus("revoke");
                try {
                    StorageOutResult sor = storageOutService.findBySpec(sop);
                    if (sor != null) {
                        if (sor.getPrivatecarCarnumbers() != null) {
                            if (sor.getPrivatecarCarnumbers().indexOf(tDispatchParam.getCarnumber()) == -1) {
                                sor.setPrivatecarCarnumbers(sor.getPrivatecarCarnumbers() + tDispatchParam.getCarnumber() + ";");
                                ToolUtil.copyProperties(sor, sop);
                                storageOutService.update(sop);
                            }
                        } else {
                            sor.setPrivatecarCarnumbers(tDispatchParam.getCarnumber() + ";");
                            ToolUtil.copyProperties(sor, sop);
                            storageOutService.update(sop);
                        }
                    }
                } catch (Exception e) {
                }
            }
            //修改车状态 为在途
            BasicPrivatecarParam bpcp2 = new BasicPrivatecarParam();
            bpcp2.setPrivatecarState("在途");
            bpcp2.setId(basicPrivatecar.getId());
            basicPrivatecarService.update(bpcp2);

            //修改车辆
            TDispatchParam tDispatchParamf = new TDispatchParam();
            tDispatchParamf.setCarId(detail.getCarId());
            tDispatchParamf.setDispatchNumber(detail.getDispatchNumber());
            TDispatchResult tDispatchResultf = tDispatchService.findByYunshuCar(tDispatchParamf, null);
            if (tDispatchResultf == null) {//如果该车没有别的派车单
                BasicPrivatecarParam bpp = new BasicPrivatecarParam();
                bpp.setPrivatecarState("空闲");
                bpp.setId(Integer.parseInt(detail.getCarId().toString()));
                basicPrivatecarService.update(bpp);
            }

            //计算满载率
            BigDecimal toovolume = new BigDecimal(detail.getToovolume());
            BigDecimal arr = new BigDecimal(100);
            BigDecimal privatecarSurevolume = new BigDecimal(basicPrivatecar.getPrivatecarSurevolume());//准载体积
            BigDecimal fulllv = toovolume.divide(privatecarSurevolume, 4, BigDecimal.ROUND_HALF_DOWN).multiply(arr).setScale(2, BigDecimal.ROUND_HALF_DOWN);//满载率  =  运输总方数   /   准载体积   *   100
            tDispatchParam.setFulllv(fulllv.toString());

            TransportDispatchParam param = new TransportDispatchParam();
            param.setDispatchNumber(detail.getDispatchNumber());
            List<TransportDispatchResult> list = transportDispatchService.findListBySpec(param);
            for (TransportDispatchResult r : list) {
                r.setCarId(tDispatchParam.getCarId());
                r.setCarnumbger(tDispatchParam.getCarnumber());
                r.setCartel(basicPrivatecar.getTel1());
                r.setDriver1(basicPrivatecar.getDriver1());
                ToolUtil.copyProperties(r, param);
                transportDispatchService.update(param);
            }

            TransportReceiptParam param2 = new TransportReceiptParam();
            param2.setDispatchNumber(detail.getDispatchNumber());
            List<TransportReceiptResult> list2 = transportReceiptService.findListBySpec(param2, null);
            for (TransportReceiptResult r : list2) {
                r.setCarId(tDispatchParam.getCarId());
                r.setCarnumber(tDispatchParam.getCarnumber());
                ToolUtil.copyProperties(r, param2);
                transportReceiptService.update(param2);
            }
            if (ToolUtil.isNotEmpty(basicPrivatecar.getPrivatecarFleetName())) {
                tDispatchParam.setCarrierId(Long.parseLong(basicPrivatecar.getPrivatecarFleetId().toString()));
                tDispatchParam.setCarrierName(basicPrivatecar.getPrivatecarFleetName());
            }
            tDispatchParam.setChexing(basicPrivatecar.getPrivatecarType());
            tDispatchParam.setZhunzailiang(basicPrivatecar.getPrivatecarSurevolume());
            tDispatchParam.setSiji(basicPrivatecar.getDriver1());
            tDispatchParam.setSijidianhua(basicPrivatecar.getTel1());
        }
        this.tDispatchService.update(tDispatchParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     */
    @RequestMapping("/editItemYunFee")
    @ResponseBody
    public ResponseData editItemYunFee(TDispatchParam tDispatchParam) {
        this.tDispatchService.update(tDispatchParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(TDispatchParam tDispatchParam) {
        this.tDispatchService.delete(tDispatchParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(TDispatchParam tDispatchParam) {
        TDispatch detail = this.tDispatchService.getById(tDispatchParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 跳转到 配送派车信息 页面
     */
    @RequestMapping("tooYhdyichang")
    public String tooYhdyichang() {
        return PREFIX + "/tooYhdyichang.html";
    }

    /**
     * 跳转到 配送派车信息 页面
     */
    @RequestMapping("tooDetailed")
    public String tooDetailed(TDispatchParam tDispatchParam) {

        return PREFIX + "/dispatchDetailed.html";
    }

    /**
     * 跳转到 配送派车信息 页面
     */
    @RequestMapping("tooDetailed2")
    public String tooDetailed2() {
        return PREFIX + "/dispatchDetailed2.html";
    }

    /**
     * 跳转到 货运订单信息 页面
     */
    @RequestMapping("tooOrderDetailed")
    public String tooOrderDetailed() {
        return PREFIX + "/orderDetailed.html";
    }

    /**
     * 查看 货运订单
     */
    @RequestMapping("/findorder")
    @ResponseBody
    public ResponseData findorder(OrderTransportParam orderTransportParam) {
        User user = userService.getcurrentUser();
        OrderTransportResult detail = orderTransportService.findBySpec(orderTransportParam, user.getOperateId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(TDispatchParam tDispatchParam, String condition, String startTime, String endTime, String driver1) {
        User user = userService.getcurrentUser();
        tDispatchParam.setDeptId(user.getDeptId());
        tDispatchParam.setDeliverId(user.getDeliverId());
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            tDispatchParam.setMoney("'" + startTime + "' and '" + endTime + "'");
        } else if (startTime == null && endTime == null) {
            startTime = DateUtil.getDate();
            endTime = DateUtil.getDate();
            tDispatchParam.setMoney("'" + startTime + "' and '" + endTime + "'");
        }
        //查看当前账户是否是承运商，若是承运商只能查看自己的数据
        String roleId = user.getRoleId();
        if (ToolUtil.isNotEmpty(roleId)) {
            for (String rId : roleId.split(",")) {
                Role byId = roleService.getById(rId);
                if (byId != null && byId.getName().contains("承运商")) {
                    BasicCarrierParam param = new BasicCarrierParam();
                    param.setUserId(user.getUserId());
                    BasicCarrierResult bySpec = basicCarrierService.findBySpec(param, user.getOperateId());
                    if (bySpec != null) {
                        tDispatchParam.setCarrierId(Long.valueOf(bySpec.getId()));
                    } else {
                        tDispatchParam.setCarrierId(-1L);
                    }
                }
            }
        }
        //
        if (ToolUtil.isNotEmpty(tDispatchParam.getCarrierNames())) {
            tDispatchParam.setCarrierNameList(tDispatchParam.getCarrierNames().split(","));
        }
        return this.tDispatchService.findPageBySpec(tDispatchParam, condition, driver1, user.getOperateId());
    }

    /**
     * 查询列表
     */
    @ResponseBody
    @RequestMapping("/list_examine")
    public LayuiPageInfo list(TDispatchParam tDispatchParam, String condition, String driver1) {
        User user = userService.getcurrentUser();
        tDispatchParam.setDeptId(user.getDeptId());
        tDispatchParam.setDeliverId(user.getDeliverId());
        return this.tDispatchService.findexaminePageBySpec(tDispatchParam, condition, driver1, user.getOperateId());
    }

    @ResponseBody
    @RequestMapping("/update5")
    public ResponseData update5(TDispatchParam tDispatchParam) {
        tDispatchParam.setStateTb("已提报");
        this.tDispatchService.update5(tDispatchParam);
        return ResponseData.success();
    }

    @ResponseBody
    @RequestMapping("/update6")
    public ResponseData update6(TDispatchParam tDispatchParam) {
        tDispatchParam.setStateTb("未提报");
        this.tDispatchService.update2(tDispatchParam);
        return ResponseData.success();
    }

    /**
     * 跳转到 打印零售发货单
     */
    @RequestMapping("printHx")
    public String printHx() {
        return PREFIX + "/printHx.html";
    }

    /**
     * 跳转到 打印零售发货单
     */
    @RequestMapping("printHxCkd")
    public String printHxCkd() {
        return PREFIX + "/printHxCkd.html";
    }

    /**
     * 打印零售发货单
     * 查询订单门店
     */
    @ResponseBody
    @RequestMapping("/getPrintStorageOut")
    public TransportDispatchResult getPrintOrderPut(String dispatchNumber, Long getLocationId) {
        User user = userService.getcurrentUser();
//    	TransportReceiptResult res = transportReceiptService.findBySpec(transportReceiptParam);
        TransportDispatchResult res = transportDispatchService.findClZjunitSumPrintBySpec(dispatchNumber, getLocationId);
        res.setPrintName(user.getName());
        return res;
    }

    /**
     * 打印查询
     * 出库单明细信息
     */
    @ResponseBody
    @RequestMapping("/getPrintStorageOutDetailed")
    public List<TransportDispatchResult> getPrintOrderPutDetailed(TransportDispatchParam transportDispatchParam) {
        List<TransportDispatchResult> list = transportDispatchService.findHxprintListBySpec(transportDispatchParam);
        List<TransportDispatchResult> res = new ArrayList<TransportDispatchResult>();
        String goodsBigtype = "";
        for (TransportDispatchResult r : list) {
            if (goodsBigtype == "") {
                if (ToolUtil.isNotEmpty(r.getGoodsBigtype())) {
                    goodsBigtype = r.getGoodsBigtype();
                    TransportDispatchResult put = new TransportDispatchResult();
                    put.setGoodsNumber(r.getGoodsBigtype());
                    res.add(put);
                    res.add(r);
                } else {
                    res.add(r);
                }
            } else {
                if (ToolUtil.isNotEmpty(r.getGoodsBigtype())) {
                    if (goodsBigtype.equals(r.getGoodsBigtype())) {
                        res.add(r);
                    } else {
                        goodsBigtype = r.getGoodsBigtype();
                        TransportDispatchResult put = new TransportDispatchResult();
                        put.setGoodsNumber(r.getGoodsBigtype());
                        res.add(put);
                        res.add(r);
                    }
                } else {
                    res.add(r);
                }
            }
        }
        return res;
    }

    /**
     * 获取运输单对应的门店出库单
     * @param transportDispatchParam
     * @return
     */
    @ResponseBody
    @RequestMapping("/getOutDetailed")
    public List<CkdPrintOby> getOutDetailed(TransportDispatchParam transportDispatchParam) {
        List<TransportDispatchResult> list = transportDispatchService.findHxLmAssociationOrder(transportDispatchParam);
        Set<String> outOrderNumberSet = new HashSet<>();
        for(TransportDispatchResult obj : list){
            if(ToolUtil.isNotEmpty(obj.getLmAssociationOrder())){
                String[] orderStr = obj.getLmAssociationOrder().split(";");
                for(String str : orderStr){
                    if(ToolUtil.isNotEmpty(str)){
                        outOrderNumberSet.add(str);
                    }
                }
            }
        }

        // 根据订单号获取订单信息
        List<HxOrderOut> list1 = this.hxOrderOutService.lambdaQuery()
                .in(HxOrderOut::getOrderOutNumber, outOrderNumberSet)
                .list();

        // 根据订单号获取订单明细
        List<HxOrderOutDetailed> list2 = this.hxOrderOutDetailedService.lambdaQuery()
                .in(HxOrderOutDetailed::getOrderOutNumber, outOrderNumberSet)
                .list();
        Map<String,List<HxOrderOutDetailed>> hxOrderOutDetailedMap = new HashMap<>();
        List<HxOrderOutDetailed> listDetailed = null;
        for(HxOrderOutDetailed obj : list2){
            if(ToolUtil.isEmpty(hxOrderOutDetailedMap.get(obj.getOrderOutNumber()))){
                listDetailed = new ArrayList<>();
                listDetailed.add(obj);
                hxOrderOutDetailedMap.put(obj.getOrderOutNumber(),listDetailed);
            }else{
                hxOrderOutDetailedMap.get(obj.getOrderOutNumber()).add(obj);
            }
        }
        List<CkdPrintOby> ckdPrintObyList = new ArrayList<>();
        List<CkdPrintItemOby> itemList;
        for(HxOrderOut obj : list1){
            itemList = new ArrayList<>();
            if(ToolUtil.isNotEmpty(hxOrderOutDetailedMap.get(obj.getOrderOutNumber()))){
                for(HxOrderOutDetailed obj1 : hxOrderOutDetailedMap.get(obj.getOrderOutNumber())){
                    itemList.add(CkdPrintItemOby.builder()
                            .goodsName(obj1.getGoodsName())
                            .goodsSpecs(obj1.getGoodsSpecs())
                            .goodsNumber(obj1.getGoodsNumber())
                            .psNum(obj1.getPsNum())
                            .unit(obj1.getUnit())
                            .goodsPrice(obj1.getGoodsPrice())
                            .outMoney(obj1.getOutMoney())
                            .notes(obj1.getNotes())
                            .getUnit(obj1.getGetUnit())
                            .build());
                }
            }

            ckdPrintObyList.add(CkdPrintOby.builder()
                    .orderOutNumber(obj.getOrderOutNumber())
                    .notes(obj.getNotes())
                    .itemList(itemList)
                    .build());
        }

        return ckdPrintObyList;
    }


    /**
     * 更新打印次数
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/getPrintStorageOut2")
    public ResponseData getPrintOrderPut2(TransportReceiptParam transportReceiptParam) {
        this.transportReceiptService.updatePrint(transportReceiptParam);
        return ResponseData.success();
    }


    /**
     * 导入页面
     */
    @RequestMapping("/toimportExcel")
    public String toimportExcel(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId, deliverId, user.getOperateId()));
        //查询可选择客户
        return "/fi/tDispatchStateTbMgr/import.html";
    }

    /**
     * 下载模板
     *
     * @throws ServletException , IOException
     */
    @RequestMapping("downloadExcel")
    public void downloadExcel(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = "assets/excel/tDispatchStateTbMgr.xlsx";
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
            OutputStream outputStream = response.getOutputStream();
            //设置下载的文件类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置下载文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("运输单提报模板" + ".xlsx").getBytes(), "iso-8859-1"));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param fileName
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping("downFileByFileName")
    public void downFileByFileName(String fileName, HttpServletResponse response) throws ServletException, IOException {
        String path = this.tmpImpPath + "/" + fileName;
        try {
            BufferedInputStream inputStream = FileUtil.getInputStream(path);
            OutputStream outputStream = response.getOutputStream();
            //设置下载的文件类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置下载文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("运输单对比结果" + ".xlsx").getBytes(), "iso-8859-1"));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 导入excel
     */
    @RequestMapping(value = "/importExcel", method = {RequestMethod.POST})
    @ResponseBody
    public ResponseData importExceNewmethodl(@RequestPart("file") MultipartFile file, Long operateId, HttpServletResponse response) {
        ResponseData data = new ResponseData();
        User user = userService.getcurrentUser();
        try {
            return tDispatchService.getExceldata(file, operateId, user, response);//处理导入数据
        } catch (Exception e) {
            data.setSuccess(false);
            e.printStackTrace();
        }
        return data;
    }

    /**
     * 跳转到 承运商装运客户统计(按客户)
     */
    @RequestMapping("/shipmentStatistics_customer")
    public String shipmentStatistics_customer(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId, deliverId, user.getOperateId()));
        return PREFIX + "/shipmentStatisticscustomer.html";
    }


    /**
     *
     * @param inwarehouseTrackParam
     * @param condition
     * @param startTime
     * @param endTime
     * @param operateId
     * @return
     */
    @ResponseBody
    @RequestMapping("/hx_daocanggenzong")
    public LayuiPageInfo hx_daocanggenzong(InwarehouseTrackParam inwarehouseTrackParam , String condition, String startTime, String endTime, Long operateId) {
        User user = userService.getcurrentUser();
        if(inwarehouseTrackParam.getOperateId() == null){
            inwarehouseTrackParam.setOperateId(user.getOperateId().toString());
        }
        LayuiPageInfo res = inwarehouseTrackService.findHx_daocanggenzong(inwarehouseTrackParam, condition, startTime, endTime, operateId);

        return res;
    }



    @RequestMapping("toUpdatexsr")
    public String toUpdatexsr(String dispatchNumber, String xlbClientId) {
        return PREFIX + "/updateqsrSel.html";
    }

    @ResponseBody
    @RequestMapping("/updatexsrList")
    public LayuiPageInfo updatexsrList(String dispatchNumber, String xlbClientId) {
        LayuiPageInfo layuiPageInfo = new LayuiPageInfo();

        TDispatchParam dispatchParam = new TDispatchParam();
        dispatchParam.setDispatchNumber(dispatchNumber);
        TDispatchResult dispatchResult = tDispatchService.findBySpec(dispatchParam, null);

        BasicCustomerParam basicCustomerParam = new BasicCustomerParam();
        basicCustomerParam.setCustomerOperateId(Integer.parseInt(dispatchResult.getOperateId().toString()));
        BasicCustomerResult cr = basicCustomerService.findBySpec(basicCustomerParam, null);

        BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
        oauth2tokenParam.setGsnumber(cr.getGsnumber());
//        oauth2tokenParam.setGsnumber("1000");
        BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);
        if (oauth2tokenResult != null && StringUtils.isNotBlank(xlbClientId)) {
            //重新修改 运单和司机的绑定关系
            String tranDriveUpdateUrl = this.hxlApiUrl + "/hxl.tms.openapi.employ.find";
            JSONObject tranDriveUpdateObj = new JSONObject();
            tranDriveUpdateObj.put("id", xlbClientId);
//            tranDriveUpdateObj.put("id", "100000007985");
            String tranDriveUpdateRes = HttpRequest.post(tranDriveUpdateUrl)
                    .timeout(60000)
                    .contentType("application/json;charset=UTF-8")
                    .header("Accept", "application/json")
                    .header("Authorization", "bearer " + oauth2tokenResult.getOauth2TokenXlb()).body(tranDriveUpdateObj.toString()).execute().body();
            JSONObject tranDriveUpdateObject = new JSONObject(tranDriveUpdateRes);

            List<UpdateqsrIby> updateqsrList = new ArrayList<>();
            if ("0".equals(tranDriveUpdateObject.get("code").toString())) {
                JSONArray dataArr = tranDriveUpdateObject.getJSONArray("data");
                if(ToolUtil.isNotEmpty(dataArr)){
                    for(Object obj : dataArr){
                        JSONObject jsonObject2 = new JSONObject(obj.toString());
                        updateqsrList.add(UpdateqsrIby.builder()
                                .userName(jsonObject2.getString("user_name"))
                                .employeeName(jsonObject2.getString("employee_name"))
                                .userTel(jsonObject2.getString("user_tel"))
                                .admin(jsonObject2.getBoolean("admin"))
                                .build());
                    }
                }
            }
            layuiPageInfo.setData(updateqsrList);
            layuiPageInfo.setCount(updateqsrList.size());
        }
        return layuiPageInfo;
    }


    /**
     * 更改签收人
     * @param updatexsrSigin
     * @return
     */
    @ResponseBody
    @RequestMapping("/updatexsr")
    public ResponseData updatexsr(UpdatexsrSiginIby updatexsrSigin) {
        if(ToolUtil.isEmpty(updatexsrSigin.getXlbClientId())){
            return ResponseData.error("未获取到门店ID，无法操作");
        }
        TDispatchParam dispatchParam = new TDispatchParam();
        dispatchParam.setDispatchNumber(updatexsrSigin.getDispatchNumber());
        TDispatchResult dispatchResult = tDispatchService.findBySpec(dispatchParam, null);
        if(ToolUtil.isEmpty(dispatchResult)){
            return ResponseData.error("运单不存在，无法操作");
        }

        if(ToolUtil.isEmpty(dispatchResult.getXlbDepartOrderId())){
            return ResponseData.error("运单未发运，无法操作");
        }

        BasicCustomerParam basicCustomerParam = new BasicCustomerParam();
        basicCustomerParam.setCustomerOperateId(Integer.parseInt(dispatchResult.getOperateId().toString()));
        BasicCustomerResult cr = basicCustomerService.findBySpec(basicCustomerParam, null);

        BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
        oauth2tokenParam.setGsnumber(cr.getGsnumber());
//        oauth2tokenParam.setGsnumber("1000");
        BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);
        if (oauth2tokenResult != null) {
            //重新修改 运单和司机的绑定关系
            String tranDriveUpdateUrl = this.hxlApiUrl + "/hxl.tms.openapi.sign.recipient.contract.forward";
            JSONObject tranDriveUpdateObj = new JSONObject();
//            tranDriveUpdateObj.put("client_id", "100000007985");
//            tranDriveUpdateObj.put("fid", "FC10013030000080");
            tranDriveUpdateObj.put("client_id", updatexsrSigin.getXlbClientId());
            tranDriveUpdateObj.put("fid", dispatchResult.getSginKey());
            tranDriveUpdateObj.put("tel", updatexsrSigin.getUserTel());
            String tranDriveUpdateRes = HttpRequest.post(tranDriveUpdateUrl)
                    .timeout(60000)
                    .contentType("application/json;charset=UTF-8")
                    .header("Accept", "application/json")
                    .header("Authorization", "bearer " + oauth2tokenResult.getOauth2TokenXlb()).body(tranDriveUpdateObj.toString()).execute().body();
            JSONObject tranDriveUpdateObject = new JSONObject(tranDriveUpdateRes);
            if (!"0".equals(tranDriveUpdateObject.get("code").toString())) {
                String msg = tranDriveUpdateObject.get("msg").toString();
                return ResponseData.error("【XLB】更换签约人：" + msg);
            }
        }else{
            return ResponseData.error("未获取到Token信息，无法操作");
        }
        return ResponseData.success();
    }

}


